I was faced with below interview question today and I came up with recursive and iterative solution as mentioned below but somehow interviewer was not happy. I am not sure why.
Given a binary search tree, find the kth smallest element in it.
Is there any better way to do this problem either in recursive or iterative way?
/*****************************************************
*
* Kth Smallest Recursive
*
******************************************************/
public int kthSmallestRecursive(TreeNode root, int k) {
int count = countNodes(root.left);
if (k <= count) {
return kthSmallestRecursive(root.left, k);
} else if (k > count + 1) {
return kthSmallestRecursive(root.right, k - 1 - count);
}
return root.data;
}
public int countNodes(TreeNode n) {
if (n == null)
return 0;
return 1 + countNodes(n.left) + countNodes(n.right);
}
/*****************************************************
*
* Kth Smallest Iterative
*
******************************************************/
public int kthSmallestIterative(TreeNode root, int k) {
Stack<TreeNode> st = new Stack<>();
while (root != null) {
st.push(root);
root = root.left;
}
while (k != 0) {
TreeNode n = st.pop();
k--;
if (k == 0)
return n.data;
TreeNode right = n.right;
while (right != null) {
st.push(right);
right = right.left;
}
}
return -1;
}
I mentioned complexity on both the above solution as O(depth of node) which is O(log n).
My iterative version takes extra space. Is there any way to do it without any extra space?