Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 97f8f94

Browse files
committed
fix: change in code, return null when node not found
1 parent 6416cfc commit 97f8f94

File tree

1 file changed

+20
-18
lines changed
  • src/_DataStructures_/Trees/BinarySearchTree/find-ancestors

1 file changed

+20
-18
lines changed
Lines changed: 20 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,31 @@
11
// eslint-disable-next-line no-unused-vars
22
const 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

4345
module.exports = findAncestors;

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /