965. Univalued Binary Tree

A binary tree is uni-valued if every node in the tree has the same value.

Given the root of a binary tree, return true if the given tree is uni-valued, or false otherwise.

solution:

class Solution(object):
    
    def __init__(self):
        self.res = set()
    def isUnivalTree(self, root):
        if root is None:
            return
        self.res.add(root.val)
        self.isUnivalTree(root.left)
        self.isUnivalTree(root.right)
        return len(self.res) == 1

__init__是类的构造函数。所述self参数是指(如对象的实例this在 C ++)

class Point:
    def __init__(self, x, y):
        self._x = x
        self._y = y

分配对象的内存时,将调用__init__方法:

x = Point(1,2)

如果要将值与对象保持在一起,则在对象的方法内使用self参数很重要。例如,如果您实现__init__方法,例如:

class Point:
    def __init__(self, x, y):
        _x = x
        _y = y

您的x和y参数将存储在堆栈中的变量中,并且当 init 方法超出范围时将被丢弃。将这些变量设置为self._x和self._y这些变量设置为Point对象的成员(在对象的生存self._y可访问)。

self变量表示对象本身的实例。大多数面向对象的语言将此作为隐藏参数传递给在对象上定义的方法。 Python 没有。您必须明确声明它。当您创建A类的实例并调用其方法时,它将自动传递,如…

# We do not pass any argument to the __init__ method
a = A()              
 # We only pass a single argument
a.method_a('Sailor!') 

__init__方法大致代表 Python 中的构造函数。当您调用A() Python 会为您创建一个对象,并将其作为第一个参数传递给__init__方法。任何其他参数(例如A(24, ‘Hello’) )也将作为参数传递 - 在这种情况下,将引发引发异常,因为构造函数不期望它们。

上一篇:[LeetCode] - 965. 单值二叉树


下一篇:c – 如果我将片段着色器附加到程序,则出现错误1282