Iterative in-order with early stop
Time O(h + k) Space O(h)Push left spine, pop, count; when the count reaches k, return the value.
root = [5, 3, 6, 2, 4, null, null, 1], k = 3stack(stack)
Step 1/3Push the left spine: 5, 3, 2, 1.
import java.util.ArrayDeque;
import java.util.Deque;
class Solution {
public int kthSmallest(TreeNode root, int k) {
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode cur = root;
while (true) {
while (cur != null) { stack.push(cur); cur = cur.left; }
cur = stack.pop();
if (--k == 0) return cur.val;
cur = cur.right;
}
}
}Verdict: Stops early.