File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 1+ # https://leetcode.com/problems/maximum-depth-of-binary-tree/
2+
3+ from typing import Optional
4+
5+ # Definition for a binary tree node.
6+ class TreeNode :
7+ def __init__ (self , val = 0 , left = None , right = None ):
8+ self .val = val
9+ self .left = left
10+ self .right = right
11+
12+ class Solution :
13+ def maxDepth_recur (self , root : Optional [TreeNode ]) -> int :
14+ """
15+ [Complexity]
16+ - TC: O(n) (모든 node를 한 번씩 방문)
17+ - SC: O(h) (call stack) (h = logn ~ n)
18+
19+ [Approach] recursive
20+ 재귀적으로 max(left subtree의 depth, right subtree의 depth) + 1 을 구하면 된다.
21+ base condition(= 현재 노드가 None인 경우)에서는 0을 반환한다.
22+ """
23+
24+ def get_max_depth (node ):
25+ # base condition
26+ if not node :
27+ return 0
28+
29+ # recur
30+ return max (get_max_depth (node .right ), get_max_depth (node .left )) + 1
31+
32+ return get_max_depth (root )
33+
34+ def maxDepth (self , root : Optional [TreeNode ]) -> int :
35+ """
36+ [Complexity]
37+ - TC: O(n) (모든 node를 한 번씩 방문)
38+ - SC: O(w) (트리의 너비) (w = 1 ~ n / 2)
39+
40+ [Approach] iterative
41+ BFS 처럼 이진 트리를 레벨 별로 순회하며 depth를 1씩 증가시킬 수 있다.
42+ """
43+ depth = 0
44+ curr_level = [root ] if root else []
45+
46+ while curr_level :
47+ next_level = []
48+ for node in curr_level :
49+ if node .left :
50+ next_level .append (node .left )
51+ if node .right :
52+ next_level .append (node .right )
53+
54+ curr_level = next_level
55+ depth += 1
56+
57+ return depth
You can’t perform that action at this time.
0 commit comments