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 a75e950

Browse files
committed
update: Find k nodes from the root
1 parent c95821c commit a75e950

File tree

4 files changed

+32
-3
lines changed

4 files changed

+32
-3
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// eslint-disable-next-line no-unused-vars
2+
const BST = require('../index');
3+
4+
function findKNodes(root, k) {
5+
let arr = [];
6+
7+
if (root === null) return [];
8+
if (k === 0) return [...arr, root.value];
9+
10+
const left = findKNodes(root.leftChild, k - 1);
11+
arr = [...arr, ...left];
12+
13+
const right = findKNodes(root.rightChild, k - 1);
14+
arr = [...arr, ...right];
15+
return arr;
16+
}
17+
18+
// create a BST
19+
// const myBST = new BST(6);
20+
21+
// myBST.add(2);
22+
// myBST.add(19);
23+
// myBST.add(14);
24+
// myBST.add(8);
25+
// myBST.add(5);
26+
// myBST.add(12);
27+
// myBST.add(33);
28+
// myBST.add(52);
29+
// myBST.add(1);
30+
31+
// console.log(findKNodes(myBST.root, 2));

‎src/_DataStructures_/Trees/BinarySearchTree/find-kth-max/index.js‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
// eslint-disable-next-line no-unused-vars
12
const BST = require('../index');
23

34
// Inorder traversal returns a sorted array

‎src/_DataStructures_/Trees/BinarySearchTree/find-kth-min/index.js‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,6 @@ function findKthMin(rootNode, k) {
3434
// myBST.add(1);
3535
// myBST.add(0);
3636

37-
// // find 3rd max
3837
// console.log(findKthMin(myBST.root, 3));
3938

4039
module.exports = findKthMin;

‎src/_DataStructures_/Trees/BinarySearchTree/height-of-bst/index.js‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,8 @@ function findHeightOfBST(root) {
2626
// myBST.add(12);
2727
// myBST.add(10);
2828

29-
// // find 3rd max
3029
// // console.log(myBST.root);
3130
// console.log(myBST.traversePreorder());
32-
// // console.log(myBST.root.rightChild);
3331
// console.log(findHeightOfBST(myBST.root));
3432

3533
module.exports = findHeightOfBST;

0 commit comments

Comments
(0)

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