Skip to content

Commit 81c88b8

Browse files
committed
update: find all ancestors of a node
1 parent ab8b038 commit 81c88b8

File tree

1 file changed

+43
-0
lines changed
  • src/_DataStructures_/Trees/BinarySearchTree/find-ancestors

1 file changed

+43
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
// eslint-disable-next-line no-unused-vars
2+
const BST = require('../index');
3+
4+
function findAncestors(root, value) {
5+
/**
6+
* search the given node and meanwhile
7+
* keep pushing the visited nodes
8+
*/
9+
let arr = [];
10+
if (root === null) return [];
11+
if (value > root.value) {
12+
// traverse right
13+
const left = findAncestors(root.rightChild, value);
14+
arr = [...arr, ...left];
15+
}
16+
if (value < root.value) {
17+
// traverse left
18+
const right = findAncestors(root.leftChild, value);
19+
arr = [...arr, ...right];
20+
}
21+
if (root.value === value) return arr;
22+
arr = [root.value, ...arr];
23+
return arr;
24+
}
25+
26+
// create a BST
27+
// const myBST = new BST(6);
28+
// myBST.add(4);
29+
// myBST.add(9);
30+
// myBST.add(2);
31+
// myBST.add(5);
32+
// myBST.add(14);
33+
// myBST.add(8);
34+
// myBST.add(12);
35+
// myBST.add(10);
36+
37+
// // find 3rd max
38+
// // console.log(myBST.root);
39+
// console.log(myBST.traversePreorder());
40+
// // console.log(myBST.root.rightChild);
41+
// console.log(findAncestors(myBST.root, 10));
42+
43+
module.exports = findAncestors;

0 commit comments

Comments
 (0)