forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0104-maximum-depth-of-binary-tree.js
50 lines (39 loc) · 1.1 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
/**
* 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 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;
}