Created
April 3, 2017 16:55
-
-
Save daartv/b979b5098a77d163f4043f6221f082dd to your computer and use it in GitHub Desktop.
Find the Kth smallest element on a Binary Search Tree
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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