Skip to content

Commit e72c709

Browse files
committed
maximum depth of binary tree
1 parent 84bc5b6 commit e72c709

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
class Solution {
2+
func maxDepthStack(_ root: TreeNode?) -> Int {
3+
guard let root = root else {
4+
return 0
5+
}
6+
var searchStack = [(TreeNode, Int)]()
7+
searchStack.append((root, 1))
8+
var maxDepth = 1
9+
10+
while searchStack.isEmpty == false {
11+
guard let popped = searchStack.popLast() else {
12+
break
13+
}
14+
maxDepth = max(popped.1, maxDepth)
15+
16+
if let left = popped.0.left {
17+
searchStack.append((left, popped.1 + 1))
18+
}
19+
20+
if let right = popped.0.right {
21+
searchStack.append((right, popped.1 + 1))
22+
}
23+
}
24+
25+
return maxDepth
26+
27+
//시간복잡도 O(n)
28+
//공간복잡도 O(n)
29+
}
30+
31+
func maxDepthRecursion(_ root: TreeNode?) -> Int {
32+
guard let root = root else {
33+
return 0
34+
}
35+
36+
return max(maxDepth(root.left), maxDepth(root.right)) + 1
37+
38+
//시간복잡도 O(n)
39+
//공간복잡도 O(n)
40+
}
41+
}
42+

0 commit comments

Comments
 (0)