1
1
/**
2
2
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
3
- * TIme O(N) | Space O(N)
3
+ * Time O(N) | Space O(N)
4
4
* @param {TreeNode } root
5
5
* @return {number }
6
6
*/
7
- var maxDepth = function ( root ) {
7
+ var maxDepth = function ( root ) {
8
8
const isBaseCase = root === null ;
9
9
if ( isBaseCase ) return 0 ;
10
10
@@ -18,11 +18,37 @@ const dfs = (root) => {
18
18
const height = Math . max ( left , right ) ;
19
19
20
20
return height + 1 ;
21
- }
21
+ } ;
22
22
23
23
/**
24
24
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
25
- * TIme O(N) | Space O(N)
25
+ * Time O(N) | Space O(N)
26
+ * @param {TreeNode } root
27
+ * @return {number }
28
+ */
29
+ var maxDepth = function ( root ) {
30
+ const isBaseCase = root === null ;
31
+ if ( isBaseCase ) return 0 ;
32
+
33
+ return iterativeDfs ( [ [ root , 1 ] ] ) ;
34
+ } ;
35
+
36
+ const iterativeDfs = ( stack , height = 0 ) => {
37
+ while ( stack . length ) {
38
+ const [ root , depth ] = stack . pop ( ) ;
39
+
40
+ height = Math . max ( height , depth ) ;
41
+
42
+ if ( root . right ) stack . push ( [ root . right , depth + 1 ] ) ;
43
+ if ( root . left ) stack . push ( [ root . left , depth + 1 ] ) ;
44
+ }
45
+
46
+ return height ;
47
+ } ;
48
+
49
+ /**
50
+ * https://leetcode.com/problems/maximum-depth-of-binary-tree/
51
+ * Time O(N) | Space O(N)
26
52
* @param {TreeNode } root
27
53
* @return {number }
28
54
*/
@@ -31,7 +57,7 @@ var maxDepth = function(root) {
31
57
if ( isBaseCase ) return 0 ;
32
58
33
59
return bfs ( [ [ root , 0 ] ] ) ;
34
- }
60
+ } ;
35
61
36
62
const bfs = ( queue , height = 0 ) => {
37
63
while ( queue . length ) {
@@ -46,5 +72,4 @@ const bfs = (queue, height = 0) => {
46
72
}
47
73
48
74
return height ;
49
- }
50
-
75
+ } ;
0 commit comments