File tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed
maximum-depth-of-binary-tree Expand file tree Collapse file tree 1 file changed +42
-0
lines changed Original file line number Diff line number Diff line change
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
+
You can’t perform that action at this time.
0 commit comments