Skip to content

Instantly share code, notes, and snippets.

@alexitaylor
Created May 22, 2017 16:57
Show Gist options
  • Save alexitaylor/93978d474fcfd0bcd1a083c218d7f15d to your computer and use it in GitHub Desktop.
Save alexitaylor/93978d474fcfd0bcd1a083c218d7f15d to your computer and use it in GitHub Desktop.
Kth Smallest Element in a BST
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
var result = null;
var count = 0;
var isFound = false;
function recur(root) {
if (root !== null && !isFound) {
recur(root.left);
count++;
if (count === k) {
result = root.val;
isFound = true;
return;
}
recur(root.right);
}
}
recur(root);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment