1
1
// eslint-disable-next-line no-unused-vars
2
2
const BST = require ( '../index' ) ;
3
3
4
- function findAncestors ( root , value ) {
4
+ function searchAndPush ( root , value , result ) {
5
5
/**
6
6
* search the given node and meanwhile
7
7
* keep pushing the visited nodes
8
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 = [ ...left , ...arr ] ;
9
+ if ( root == null ) {
10
+ return false ;
11
+ }
12
+ if ( root . value === value ) {
13
+ return true ;
15
14
}
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 ;
20
21
}
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 ;
24
29
}
25
30
26
31
// create a BST
@@ -34,10 +39,7 @@ function findAncestors(root, value) {
34
39
// myBST.add(12);
35
40
// myBST.add(10);
36
41
37
- // // find 3rd max
38
- // // console.log(myBST.root);
39
- // console.log(myBST.traversePreorder());
40
- // // console.log(myBST.root.rightChild);
41
42
// console.log(findAncestors(myBST.root, 10));
43
+ // console.log(findAncestors(myBST.root, 101));
42
44
43
45
module . exports = findAncestors ;
0 commit comments