Skip to content

Instantly share code, notes, and snippets.

@daartv
Created April 3, 2017 16:55
Show Gist options
  • Save daartv/b979b5098a77d163f4043f6221f082dd to your computer and use it in GitHub Desktop.
Save daartv/b979b5098a77d163f4043f6221f082dd to your computer and use it in GitHub Desktop.
Find the Kth smallest element on a Binary Search Tree
/**
* 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) {
//Create a storage array for all the values in the tree
var values = [];
//Go to the root, push the value of the root to the array
var traverseTree = function (node) {
values.push(node.val);
//if there's a right
if (node.right){
//push that value into the array
values.push(node.right);
//if there's a left
} else if (node.left) {
//push that value into the array
values.push(node.right)
} else {
return
}
traverseTree(root.right)
traverseTree(root.left)
}
return values
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment