Skip to content

Commit 28e73b5

Browse files
committed
update: fix the edge case using array approach
1 parent 97f8f94 commit 28e73b5

File tree

1 file changed

+21
-17
lines changed
  • src/_DataStructures_/Trees/BinarySearchTree/find-ancestors

1 file changed

+21
-17
lines changed

src/_DataStructures_/Trees/BinarySearchTree/find-ancestors/index.js

+21-17
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,35 @@
11
// eslint-disable-next-line no-unused-vars
22
const BST = require('../index');
33

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) {
59
/**
610
* search the given node and meanwhile
711
* keep pushing the visited nodes
812
*/
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+
}
1020
return false;
1121
}
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;
2129
}
22-
return false;
23-
}
2430

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;
2933
}
3034

3135
// create a BST

0 commit comments

Comments
 (0)