Skip to content

Instantly share code, notes, and snippets.

@shailrshah
Created October 21, 2017 00:26
Show Gist options
  • Save shailrshah/e67ab882fd0e4c0ebd1748abe6c0325a to your computer and use it in GitHub Desktop.
Save shailrshah/e67ab882fd0e4c0ebd1748abe6c0325a to your computer and use it in GitHub Desktop.
Find the Kth smallest element in a BST.
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