Created
October 21, 2017 00:26
-
-
Save shailrshah/e67ab882fd0e4c0ebd1748abe6c0325a to your computer and use it in GitHub Desktop.
Find the Kth smallest element in a 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
static int count, element; | |
private static void kthSmallestHelper(TreeNode root, int k) { | |
if(root == null) | |
return; | |
kthSmallestHelper(root.left, k); | |
if(k == ++count) { | |
element = root.val; | |
return; | |
} | |
else | |
kthSmallestHelper(root.right, k); | |
} | |
public int kthSmallest(TreeNode root, int k) { | |
count = 0; | |
element = root.val; | |
kthSmallestHelper(root, k); | |
return element; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment