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 05184c4

Browse files
committed
update: find k-th max in BST
1 parent 699fd82 commit 05184c4

File tree

1 file changed

+35
-0
lines changed
  • src/_DataStructures_/Trees/BST/find-kth-max

1 file changed

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

0 commit comments

Comments
(0)

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