-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path二叉搜索树的最近公共祖先.js
More file actions
59 lines (51 loc) · 904 Bytes
/
二叉搜索树的最近公共祖先.js
File metadata and controls
59 lines (51 loc) · 904 Bytes
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
// 普通树
function findParentRoot (node, p, q) {
if (!node || node.value === q || node.value === p) return node
const left = findParentRoot(node.left, p, q)
const right = findParentRoot(node.right, p, q)
if (left && !right) {
return left
}
if (!left && right) {
return right
}
if (left && right) {
return node
}
}
// 二叉树
function findParentTree(node, p, q) {
let root = node
while (root) {
if (node.value > p && node.value > q) {
root = root.left
} else if (node.value < p && node.value < q) {
root = root.right
} else {
return root
}
}
}
const node = {
value: 10,
left: {
value: 9,
left: {
value: 3
},
right: {
value: 5
}
},
right: {
value: 11,
left: {
value: 8
},
right: {
value: 7
}
}
}
const rs = findParentRoot(node, 7, 8)
console.log(rs)