Skip to content

Commit 71673bc

Browse files
committed
solution: maximum-depth-of-binary-tree
1 parent f056ea5 commit 71673bc

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed
Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
"""
2+
# Intuition
3+
트리 전체 순회
4+
5+
# Approach
6+
-
7+
8+
# Complexity
9+
time : O(N)
10+
space : O(N)
11+
"""
12+
13+
# Definition for a binary tree node.
14+
# class TreeNode:
15+
# def __init__(self, val=0, left=None, right=None):
16+
# self.val = val
17+
# self.left = left
18+
# self.right = right
19+
20+
21+
# Stack (top-down)
22+
class Solution:
23+
def maxDepth(self, root: Optional[TreeNode]) -> int:
24+
25+
# edge case
26+
if not root:
27+
return 0
28+
29+
max_depth = 0
30+
stack = [(root, 1)]
31+
32+
while stack:
33+
node, depth = stack.pop()
34+
35+
max_depth = max(depth, max_depth) # update depth
36+
37+
if node.left:
38+
stack.append((node.left, depth + 1))
39+
if node.right:
40+
stack.append((node.right, depth + 1))
41+
42+
return max_depth
43+
44+
45+
""" 재귀 (bottom-top)
46+
# max_depth : 현재 노드를 기준으로, 좌측과 우측 자식 트리 중 max_depth가 큰 값을 선택해 + 1
47+
48+
class Solution:
49+
def maxDepth(self, root: Optional[TreeNode]) -> int:
50+
51+
# 기저조건
52+
if not root:
53+
return 0
54+
55+
return 1 + max(
56+
self.maxDepth(root.left),
57+
self.maxDepth(root.right),
58+
)
59+
"""

0 commit comments

Comments
 (0)