Skip to content

Commit 9468614

Browse files
committed
feat: add maximum-depth-of-binary-tree sol
1 parent caca329 commit 9468614

File tree

2 files changed

+45
-4
lines changed

2 files changed

+45
-4
lines changed
Lines changed: 44 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,56 @@
11
"""
22
[문제풀이]
33
# Inputs
4-
4+
- 이진 트리의 root
55
# Outputs
6-
6+
- 가장 최고 깊이
77
# Constraints
8-
8+
The number of nodes in the tree is in the range [0, 104].
9+
-100 <= Node.val <= 100
910
# Ideas
11+
dfs, 즉 재귀 돌면서
12+
depth 를 max로 업데이트 하면 될 것 같은 느낌?
1013
1114
[회고]
15+
내 풀이는 정답
16+
해설 방법도 궁금하여 참고
17+
-> TC, SC도 파악하는 연습!
18+
19+
TC: o(n)
20+
SC: o(n)
1221
1322
"""
1423

24+
# 내 풀이
25+
# Definition for a binary tree node.
26+
# class TreeNode:
27+
# def __init__(self, val=0, left=None, right=None):
28+
# self.val = val
29+
# self.left = left
30+
# self.right = right
31+
class Solution:
32+
def maxDepth(self, root: Optional[TreeNode]) -> int:
33+
def dfs(node, depth):
34+
if node is None:
35+
return depth - 1
36+
37+
return max(dfs(node.left, depth + 1), dfs(node.right, depth + 1))
38+
39+
return dfs(root, 1)
40+
# 해설
41+
# bfs 풀이도 존재
42+
class Solution:
43+
def maxDepth(self, root: Optional[TreeNode]) -> int:
44+
if not root:
45+
return 0
46+
max_depth = 0
47+
stack = [(root, 1)]
48+
while stack:
49+
node, depth = stack.pop()
50+
max_depth = max(depth, max_depth)
51+
if node.left:
52+
stack.append((node.left, depth + 1))
53+
if node.right:
54+
stack.append((node.right, depth + 1))
55+
return max_depth
1556

merge-two-sorted-lists/shinsj4653.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,4 +57,4 @@ def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) ->
5757

5858
head.next = list1 or list2
5959
return retList.next
60-
60+

0 commit comments

Comments
 (0)