Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit a016618

Browse files
committed
feat: 二叉树最近公共祖先
1 parent 5aef9dc commit a016618

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
let T = require("../工具/二叉树")
2+
3+
let lowestCommonAncestor = function (root, p, q) {
4+
let findAndCreate = (node, target, depth) => {
5+
if (node !== target) {
6+
let findInLeft
7+
if (node.left) {
8+
node.left.parent = node
9+
findInLeft = findAndCreate(node.left, target, depth + 1)
10+
}
11+
12+
if (findInLeft) {
13+
return findInLeft
14+
} else {
15+
if (node.right) {
16+
node.right.parent = node
17+
return findAndCreate(node.right, target, depth + 1)
18+
}
19+
}
20+
} else {
21+
return {
22+
depth,
23+
node,
24+
}
25+
}
26+
}
27+
28+
let findP = findAndCreate(root, p, 0) || {}
29+
let findQ = findAndCreate(root, q, 0) || {}
30+
31+
let cur = findP.depth > findQ.depth ? findQ.node : findP.node
32+
33+
while (!(isAncestor(cur, p) && isAncestor(cur, q))) {
34+
cur = cur.parent
35+
}
36+
37+
return cur
38+
}
39+
40+
function isAncestor(node, target) {
41+
if (!node) {
42+
return false
43+
}
44+
if (node !== target) {
45+
return !!(isAncestor(node.left, target) || isAncestor(node.right, target))
46+
} else {
47+
return true
48+
}
49+
}
50+
51+
let l
52+
let r
53+
let t = new T(3)
54+
t.left = l = new T(5)
55+
t.right = r = new T(1)
56+
57+
console.log(lowestCommonAncestor(t, l, r))

0 commit comments

Comments
 (0)