I was faced with below interview question today and I came up with below solution 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 or more efficient way to do this problem?
/*****************************************************
*
* 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 time and space complexity as O(n). My iterative version takes extra space. Is there any way to do it without any extra space?
O(k)
memory acceptable? \$\endgroup\$TreeNode
class? \$\endgroup\$sr
(root.clone()
?) withsr.right = root
, increasek
and get rid of the duplicated push left-path. \$\endgroup\$