代码改变世界

[LeetCode] 559. Maximum Depth of N-ary Tree_Easy tag: DFS

2018-08-09 09:00  Johnson_强生仔仔  阅读(265)  评论(0编辑  收藏  举报

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.

For example, given a 3-ary tree:

 

 

We should return its max depth, which is 3.

Note:

  1. The depth of the tree is at most 1000.
  2. The total number of nodes is at most 5000.

 

12/12/2019 Update: Code 可以用更简介的方式, 2 lines。 

05/11/2020 Update: 利用map。

这个题目就是用DFS recursive啦.

 

 

 

Code:

class Solution:
    def maxDepthNarry(self, root):
        if not root: return 0
        temp = []
        for each in root.children:
            temp.append(self.maxDepthNarry(each))
        return 1 + max(temp + [0])

 


Code2:

class Solution:
    def maxDepth(self, root):
        if not root: return 0
        return 1 + max([self.maxDepth(child) for child in root.children] + [0]) # + [0] because children might be [], then max([]) will throw error. 

 

Code3:

class Solution:
    def maxDepth(self, root):
        if not root: return 0
        children = map(self.maxDepth, root.children)
        return 1 + max(children + [0])  #note: max([]) will throw error.