Created
May 22, 2017 16:57
-
-
Save alexitaylor/93978d474fcfd0bcd1a083c218d7f15d to your computer and use it in GitHub Desktop.
Kth Smallest Element in a BST
This file contains 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) { | |
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