Skip to content

Instantly share code, notes, and snippets.

@jykim16
Created August 28, 2017 16:57
Show Gist options
  • Save jykim16/65114a39e15d2bcad70980fcda430c25 to your computer and use it in GitHub Desktop.
Save jykim16/65114a39e15d2bcad70980fcda430c25 to your computer and use it in GitHub Desktop.
kth-smallest-in-bst
var kthSmallest = function(root, k) {
let kSmallestElement = NaN;
let findLastKNodes = (node, isRightNode, parentCountFromLeftTree) => {
var nthElement = 1;
if(node.left) {
nthElement += findLastKNodes(node.left, isRightNode);
}
if (node.right) {
findLastKNodes(node.right, true, nthElement);
nthElement += 1;
}
if(isRightNode) {
nthElement += parentCountFromLeftTree;
}
if (nthElement === k) {
kSmallestElement = node.val;
}
return nthElement;
}
findLastKNodes(root, false)
return kSmallestElement;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment