Skip to content

Commit c376f77

Browse files
committed
[:solved] #227
1 parent a3302b3 commit c376f77

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# idea : DFS
2+
3+
# time : O(n)
4+
# space : O(n)
5+
6+
class Solution:
7+
def maxDepth(self, root: Optional[TreeNode]) -> int:
8+
# edge case
9+
if not root:
10+
return 0
11+
max_depth = 0
12+
stack = [(root, 1)]
13+
while stack:
14+
node, depth = stack.pop()
15+
max_depth = max(depth, max_depth)
16+
if node.left:
17+
stack.append((node.left, depth+1))
18+
if node.right:
19+
stack.append((node.right, depth+1))
20+
return max_depth
21+
22+
# another way : Down-top : recursive
23+
# class Solution:
24+
# def maxDepth(self, root: Optional[TreeNode]) -> int:
25+
# if not root:
26+
# return 0
27+
# return 1 + max(
28+
# self.maxDepth(root.left),
29+
# self.maxDepth(root.right)
30+
# )
31+
32+
33+
34+
35+
36+
37+
38+

0 commit comments

Comments
 (0)