forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0104-maximum-depth-of-binary-tree.js
75 lines (59 loc) · 1.68 KB
/
0104-maximum-depth-of-binary-tree.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return 0;
return dfs(root);
};
const dfs = (root) => {
const left = maxDepth(root.left);
const right = maxDepth(root.right);
const height = Math.max(left, right);
return height + 1;
};
/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return 0;
return iterativeDfs([[root, 1]]);
};
const iterativeDfs = (stack, height = 0) => {
while (stack.length) {
const [root, depth] = stack.pop();
height = Math.max(height, depth);
if (root.right) stack.push([root.right, depth + 1]);
if (root.left) stack.push([root.left, depth + 1]);
}
return height;
};
/**
* https://leetcode.com/problems/maximum-depth-of-binary-tree/
* Time O(N) | Space O(N)
* @param {TreeNode} root
* @return {number}
*/
var maxDepth = function(root) {
const isBaseCase = root === null;
if (isBaseCase) return 0;
return bfs([[ root, 0 ]]);
};
const bfs = (queue, height = 0) => {
while (queue.length) {
for (let i = (queue.length - 1); 0 <= i; i--) {
const [ root, depth ] = queue.shift();
height = Math.max(height, (depth + 1));
if (root.left) queue.push([ root.left, (depth + 1) ]);
if (root.right) queue.push([ root.right, (depth + 1) ]);
}
}
return height;
};