"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
val:节点的值
children:一个列表,列表保存所有子节点
"""
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
if not root.children: # 不要用if x is None , [] 不等于 None
return 1
depth = 1 + max(self.maxDepth(i) for i in root.children)
return depth
Tips:
if x is None , if not x 区别:
使用if not x这种写法的前提是:必须清楚x等于None, False, 空字符串"", 0, 空列表[], 空字典{}, 空元组()时对你的判断没有影响才行 。
In [9]: x=[1] In [10]: not x Out[10]: False In [11]: y=[] In [12]: not y Out[12]: True In [13]: y is None Out[13]: False