Created
August 28, 2017 16:57
-
-
Save jykim16/65114a39e15d2bcad70980fcda430c25 to your computer and use it in GitHub Desktop.
kth-smallest-in-bst
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
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