Given a n-ary tree, find its maximum depth.
The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.
Nary-Tree input serialization is represented in their level order traversal, each group of children is separated by the null value (See examples).
一道求最大深度的题。
目前只用了bfs方法做。思路比较简单如下所示。
跟之前有区别的是这个Node有别于TreeNode,不再是left和right,而是一个children,这个children是一个list,所以处理起来有点不一样。
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:return 0
bfs=[root]
deepth=0
while bfs:
deepth+=1
tempnode=[]
while bfs:
node = bfs.pop()
if node.children:
tempnode+=node.children
bfs=tempnode
return deepth