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 0bf9860

Browse files
committed
update: find kth min & throw error for invalid K
1 parent 93af26e commit 0bf9860

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,9 @@ function inOrderTraversal(root) {
1313

1414
function findKthMax(rootNode, k) {
1515
const arr = inOrderTraversal(rootNode);
16+
if (k < 0 || k > arr.lenth) {
17+
throw new Error('Invalid value for K');
18+
}
1619
return arr[arr.length - k];
1720
}
1821

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
// eslint-disable-next-line no-unused-vars
2+
const BST = require('../index');
3+
4+
// Inorder traversal returns a sorted array
5+
function inOrderTraversal(root) {
6+
if (root === null) return [];
7+
let arr = [];
8+
// traverse left
9+
const left = inOrderTraversal(root.leftChild);
10+
arr = [...left, root.value];
11+
const right = inOrderTraversal(root.rightChild);
12+
return [...arr, ...right];
13+
}
14+
15+
function findKthMin(rootNode, k) {
16+
const arr = inOrderTraversal(rootNode);
17+
if (k < 0 || k > arr.lenth) {
18+
throw new Error('Invalid value for K');
19+
}
20+
return arr[k - 1];
21+
}
22+
23+
// // create a BST
24+
// const myBST = new BST(6);
25+
26+
// myBST.add(2);
27+
// myBST.add(19);
28+
// myBST.add(14);
29+
// myBST.add(8);
30+
// myBST.add(5);
31+
// myBST.add(12);
32+
// myBST.add(33);
33+
// myBST.add(52);
34+
// myBST.add(1);
35+
// myBST.add(0);
36+
37+
// // find 3rd max
38+
// console.log(findKthMin(myBST.root, 3));
39+
40+
module.exports = findKthMin;

0 commit comments

Comments
(0)

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