11// eslint-disable-next-line no-unused-vars
22const BST = require ( '../index' ) ;
33
4- function findAncestors ( root , value ) {
4+ function searchAndPush ( root , value , result ) {
55 /**
66 * search the given node and meanwhile
77 * keep pushing the visited nodes
88 */
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 = [ ...left , ...arr ] ;
9+ if ( root == null ) {
10+ return false ;
11+ }
12+ if ( root . value === value ) {
13+ return true ;
1514 }
16- if ( value < root . value ) {
17- // traverse left
18- const right = findAncestors ( root . leftChild , value ) ;
19- arr = [ ...right , ...arr ] ;
15+ if (
16+ searchAndPush ( root . leftChild , value , result )
17+ || searchAndPush ( root . rightChild , value , result )
18+ ) {
19+ result . push ( root . value ) ;
20+ return true ;
2021 }
21- if ( root . value === value ) return arr ;
22- arr = [ ...arr , root . value ] ;
23- return arr ;
22+ return false ;
23+ }
24+
25+ function findAncestors ( root , value ) {
26+ const result = [ ] ;
27+ searchAndPush ( root , value , result ) ;
28+ return result ;
2429}
2530
2631// create a BST
@@ -34,10 +39,7 @@ function findAncestors(root, value) {
3439// myBST.add(12);
3540// myBST.add(10);
3641
37- // // find 3rd max
38- // // console.log(myBST.root);
39- // console.log(myBST.traversePreorder());
40- // // console.log(myBST.root.rightChild);
4142// console.log(findAncestors(myBST.root, 10));
43+ // console.log(findAncestors(myBST.root, 101));
4244
4345module . exports = findAncestors ;
0 commit comments