tech-cow/leetcode

559. Maximum Depth of N-ary Tree

tech-cow opened this issue · 0 comments

第一刷

看答案前:
不知道为什么 max() 会接收到一个empty array

原因:
因为这题需要在当前层,dereference root.children, 所以要给root.children写一个base case...
不然的话,我们永远无法触及base case..

错误代码

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        level_max = []
        for child in root.children:
            level_max.append(self.maxDepth(child)) 
        return max(level_max) + 1

正确代码

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        if not root.children: return 1
        level_max = []
        for child in root.children:
            level_max.append(self.maxDepth(child)) 
        return max(level_max) + 1

不需要Temp Array方法

bug-free

class Solution(object):
    def maxDepth(self, root):
        if not root: return 0
        if not root.children: return 1
        height = 0
        for child in root.children:
            height = max(height, self.maxDepth(child))
        return height + 1