Search

Maximum Depth of N-ary Tree

문제 설명 : 제공된 트리의 max depth 를 구한다.
풀이 방법
자식 노드를 탐색할 때마다 전역 변수인 max_depth를 갱신한다.
시간복잡도 : O(N)O(N)
성공 코드
""" # Definition for a Node. class Node: def __init__(self, val=None, children=None): self.val = val self.children = children """ class Solution: def maxDepth(self, root: 'Node') -> int: self.max_depth = 0 def search_tree(node, depth): if not node.children: self.max_depth = max(self.max_depth, depth) for child_node in node.children: search_tree(child_node, depth + 1) if root: search_tree(root, 1) return self.max_depth
Python
복사