|
1 | 1 | // eslint-disable-next-line no-unused-vars |
2 | 2 | const BST = require('../index'); |
3 | 3 |
|
4 | | -function searchAndPush(root, value, result) { |
| 4 | +/** You should go through this conversation here: |
| 5 | + * https://github.com/knaxus/problem-solving-javascript/pull/63 |
| 6 | + */ |
| 7 | + |
| 8 | +function findAncestors(root, value) { |
5 | 9 | /** |
6 | 10 | * search the given node and meanwhile |
7 | 11 | * keep pushing the visited nodes |
8 | 12 | */ |
9 | | - if (root == null) { |
| 13 | + if (root === null) return false; |
| 14 | + |
| 15 | + if (value < root.value) { |
| 16 | + const left = findAncestors(root.leftChild, value); |
| 17 | + if (left) { |
| 18 | + return [...left, root.value]; |
| 19 | + } |
10 | 20 | return false; |
11 | 21 | } |
12 | | - if (root.value === value) { |
13 | | - return true; |
14 | | - } |
15 | | - if ( |
16 | | - searchAndPush(root.leftChild, value, result) |
17 | | - || searchAndPush(root.rightChild, value, result) |
18 | | - ) { |
19 | | - result.push(root.value); |
20 | | - return true; |
| 22 | + |
| 23 | + if (value > root.value) { |
| 24 | + const right = findAncestors(root.rightChild, value); |
| 25 | + if (right) { |
| 26 | + return [...right, root.value]; |
| 27 | + } |
| 28 | + return false; |
21 | 29 | } |
22 | | - return false; |
23 | | -} |
24 | 30 |
|
25 | | -function findAncestors(root, value) { |
26 | | - const result = []; |
27 | | - searchAndPush(root, value, result); |
28 | | - return result; |
| 31 | + if (value === root.value) return []; |
| 32 | + return false; |
29 | 33 | } |
30 | 34 |
|
31 | 35 | // create a BST |
|
0 commit comments