Skip to content

Commit db47f7c

Browse files
committedJul 19, 2023
Update 0104: Add iterative DFS solution (javascript)
1 parent f536d27 commit db47f7c

File tree

1 file changed

+32
-7
lines changed

1 file changed

+32
-7
lines changed
 

‎javascript/0104-maximum-depth-of-binary-tree.js

+32-7
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,10 @@
11
/**
22
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
3-
* TIme O(N) | Space O(N)
3+
* Time O(N) | Space O(N)
44
* @param {TreeNode} root
55
* @return {number}
66
*/
7-
var maxDepth = function(root) {
7+
var maxDepth = function(root) {
88
const isBaseCase = root === null;
99
if (isBaseCase) return 0;
1010

@@ -18,11 +18,37 @@ const dfs = (root) => {
1818
const height = Math.max(left, right);
1919

2020
return height + 1;
21-
}
21+
};
2222

2323
/**
2424
* 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)
2652
* @param {TreeNode} root
2753
* @return {number}
2854
*/
@@ -31,7 +57,7 @@ var maxDepth = function(root) {
3157
if (isBaseCase) return 0;
3258

3359
return bfs([[ root, 0 ]]);
34-
}
60+
};
3561

3662
const bfs = (queue, height = 0) => {
3763
while (queue.length) {
@@ -46,5 +72,4 @@ const bfs = (queue, height = 0) => {
4672
}
4773

4874
return height;
49-
}
50-
75+
};

0 commit comments

Comments
 (0)
Please sign in to comment.