-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1123-lowest-common-ancestor-of-deepest-leaves.js
97 lines (90 loc) · 2.16 KB
/
1123-lowest-common-ancestor-of-deepest-leaves.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
const lcaDeepestLeaves = function(root) {
let maxDepth = 0, lcaNode = null
function lca(node, depth) {
if(node == null) return depth - 1
maxDepth = Math.max(depth, maxDepth)
const left = lca(node.left, depth + 1)
const right = lca(node.right, depth + 1)
if(left === maxDepth && right === maxDepth) {
lcaNode = node
}
return Math.max(left, right)
}
lca(root, 0)
return lcaNode
};
// another
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @return {TreeNode}
*/
const lcaDeepestLeaves = function(root) {
if (root === null) return null
const getHeight = root => {
if (root === null) return 0
const res = Math.max(getHeight(root.left), getHeight(root.right)) + 1
return res
}
if (getHeight(root.left) === getHeight(root.right)) {
return root
} else if (getHeight(root.left) > getHeight(root.right)) {
return lcaDeepestLeaves(root.left)
} else {
return lcaDeepestLeaves(root.right)
}
}
// BFS
const lcaDeepestLeaves = function(root) {
let current = [root];
let level = 0;
let last = [];
while(current.length) {
let next = [];
for (var i = 0; i < current.length; i++) {
if (current[i].left) {
current[i].left.parent = current[i];
next.push(current[i].left);
}
if (current[i].right) {
current[i].right.parent = current[i];
next.push(current[i].right);
}
}
last = current;
current = next;
}
let parent = last[0].parent;
if (!parent) {
return last[0];
}
while(last.length > 1) {
let next = [];
for (var i = 0; i < last.length; i++) {
newParent = last[i].parent;
if (!next.includes(newParent)) {
next.push(newParent);
}
}
last = next;
}
return last[0];
};