559. N叉树的最大深度
方法一:BFS模板的应用。
总结的DFS、BFS模板参考:https://www.cnblogs.com/panweiwei/p/13065661.html
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root:
return 0
if not root.children:
return 1
res = 0
stack = [root]
while stack:
sizeStack = len(stack)
for i in range(sizeStack):
node = stack.pop(0)
for item in node.children:
if item:
stack.append(item)
res += 1
return res
方法二:DFS模板的应用。
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if not root:
return 0
if not root.children:
return 1
return max(1+self.maxDepth(child) for child in root.children)