-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaxDepthBinTree.js
More file actions
68 lines (56 loc) · 1.33 KB
/
Copy pathmaxDepthBinTree.js
File metadata and controls
68 lines (56 loc) · 1.33 KB
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
class TreeNode {
constructor(val, left = null, right = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function arrayToTree(arr) {
if (!arr.length) return null;
let root = new TreeNode(arr[0]);
let queue = [root];
let i = 1;
while (queue.length && i < arr.length) {
let current = queue.shift();
if (arr[i] != null) {
current.left = new TreeNode(arr[i]);
queue.push(current.left);
}
i++;
if (arr[i] != null) {
current.right = new TreeNode(arr[i]);
queue.push(current.right);
}
i++;
}
return root;
}
function treeToArray(root) {
if (!root) return [];
let result = [];
let queue = [root];
while (queue.length) {
let node = queue.shift();
if (node) {
result.push(node.val);
queue.push(node.left);
queue.push(node.right);
} else {
result.push(null);
}
}
while (result[result.length - 1] === null) {
result.pop();
}
return result;
}
const root1 = arrayToTree([3, 9, 20, null, null, 15, 7]);
const root2 = arrayToTree([1, null, 2]);
function maxDepth(root) {
if (root == null) {
return 0;
}
return Math.max(maxDepth(root["left"]), maxDepth(root["right"])) + 1;
}
console.log(`Maximum depth of tree 1 is: ${maxDepth(root1)}`);
console.log(`Maximum depth of tree 2 is: ${maxDepth(root2)}`);