Skip to content

Latest commit

 

History

History
32 lines (28 loc) · 737 Bytes

559.md

File metadata and controls

32 lines (28 loc) · 737 Bytes

559. Maximum Depth of N-ary Tree

Solution 1 (time O(n), space O(1))

"""
# Definition for a Node.
class Node(object):
    def __init__(self, val=None, children=None):
        self.val = val
        self.children = children
"""

class Solution(object):
    def maxDepth(self, root):
        """
        :type root: Node
        :rtype: int
        """
        self.ans = 0
        _ = self._dfs(root)
        return self.ans
    
    def _dfs(self, root):
        if not root:
            return 0
        cur_ans = 0
        for cur_node in root.children:
            cur_ans = max(cur_ans, self._dfs(cur_node))
        self.ans = max(self.ans, cur_ans + 1)
        return cur_ans + 1