Data Structures19 sections · 729 units
Open in Course

Kth Smallest Solution

Stop at kth node

Iterative inorder, counting as you go:

def kthSmallest(root, k):
    stack = []
    current = root
    while True:
        while current:
            stack.append(current)
            current = current.left
        current = stack.pop()
        k -= 1
        if k == 0:
            return current.val
        current = current.right

Time: O(h+k)O(h + k). You descend to the leftmost node (O(h)O(h)), then visit kk nodes.

Space: O(h)O(h) for the stack.

For the follow-up: augment each node with the size of its left subtree. Then you can find the kth smallest in O(h)O(h) time by comparing kk with subtree sizes.