Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

3 New Problems on BST #63

Merged
merged 19 commits into from
Oct 11, 2019
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
update: find k-th max in BST
  • Loading branch information
ashokdey committed Oct 10, 2019
commit 05184c42686e0e9d56e23706a39cc9a881a0fadc
35 changes: 35 additions & 0 deletions src/_DataStructures_/Trees/BST/find-kth-max/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
const BST = require('../index');

// Inorder traversal returns a sorted array
function inOrderTraversal(root) {
if (root === null) return [];
let arr = [];
// traverse left
const left = inOrderTraversal(root.leftChild);
arr = [...left, root.value];
const right = inOrderTraversal(root.rightChild);
return [...arr, ...right];
}

function findKthMax(rootNode, k) {
const arr = inOrderTraversal(rootNode);
return arr[arr.length - k];
}

// // create a BST
// const myBST = new BST(6);

// myBST.add(2);
// myBST.add(19);
// myBST.add(14);
// myBST.add(8);
// myBST.add(5);
// myBST.add(12);
// myBST.add(33);
// myBST.add(52);
// myBST.add(1);

// // find 3rd max
// console.log(findKthMax(myBST.root, 3));

module.exports = findKthMax;