Skip to content

559. Maximum Depth of N-ary Tree #61

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
tech-cow opened this issue Aug 5, 2019 · 0 comments
Closed

559. Maximum Depth of N-ary Tree #61

tech-cow opened this issue Aug 5, 2019 · 0 comments

Comments

@tech-cow
Copy link
Owner

tech-cow commented Aug 5, 2019

第一刷

看答案前:
不知道为什么 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant