-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.ts
45 lines (43 loc) · 1.04 KB
/
solution.ts
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
/**
* Definition for a binary tree node.
* class Node {
* val: number
* left: Node | null
* right: Node | null
* parent: Node | null
* constructor(val?: number, left?: Node | null, right?: Node | null, parent?: Node | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* this.parent = (parent===undefined ? null : parent)
* }
* }
*/
function lowestCommonAncestor (p: Node | null, q: Node | null): Node | null {
if (!p || !q) {
return null;
}
let depthP = getDepth(p);
let depthQ = getDepth(q);
while (depthP > depthQ) {
p = p.parent;
depthP--;
}
while (depthQ > depthP) {
q = q.parent;
depthQ--;
}
while (p !== q) {
p = p.parent;
q = q.parent;
}
return p;
}
function getDepth (root:Node) {
let result = 0;
while (root) {
result++;
root = root.parent;
}
return result;
}