xyz Interview Question
abcsCountry: India
I think the author meant BST.
just "binary tree" is senseless, because he could just write "given an unsorted array".
using a max-heap (instead of a min-heap) is faster. insert the first n elements from the tree to the heap, then for each additional element, if it is higher than the top of the heap, pop the heap and push the new element. After inserting all elements, we have the nth smallest item on the top of the heap. The time complexity is k log n (where k = # items in tree) vs k log k.
Your solution seems clever, but it does not give any advantage, asymptotically speaking. here is why, your time complexity is: k log n, as max_heapify() takes log n for each (k - n) node. however, k log n is O(k).
if follow min-heap, it takes O(k) to build the min heap. And then, it will take n times log k to find the n-th smallest element, where each extraction of smallest element takes log k to max_heapify. So, it's k + n log k, which is still O(k).
but, as I said, asymptotically speaking ... you still have a great angel
in case of arbitrary binary tree without any order of nodes the algorithm is the following:
1) re-arrange nodes to build a min-heap (in-place due to just re-arrangement of nodes). O(n).
2) k times call extract-min O(1) and min-heapify O( k log n).
Worst case is O(n log n) in case the kth smallest element is the greatest one by coincidence.
public int findKthSmallest(BinaryTreeNode<Integer> root, int k) {
if (null == root)
return -1;
int n = BinaryTree.size(root);
int a[] = new int[n];
inorder(root, a);
Arrays.sort(a);
return a[k - 1];
}
int i = 0;
public void inorder(BinaryTreeNode<Integer> root, int[] a) {
if (root != null) {
inorder(root.left, a);
a[i++] = root.data;
inorder(root.right, a);
}
}
Iterative version
public int kthSmallest(TreeNode root, int k) {
int h = 0;
Stack<TreeNode> stack = new Stack<>();
TreeNode current = root;
while (!stack.isEmpty() || current != null) {
if (current!= null) {
stack.add(current);
current = current.left;
}
else {
h += 1;
current = stack.pop();
if(h == k)
return current.val;
current = current.right;
}
}
return 0;
}
InOrder traversal. But counter starts incrementing after you reach the left most node (including it).
- zr.roman February 06, 2016Return current node when the counter is equal to n.