Skip to lesson

Using sorted order

Inorder traversal unlocks sorted stream capabilities including rank queries and iterator patterns.

Finding the kth smallest element in a BST

Because inorder traversal visits nodes in ascending order, it directly yields sorted ranks. A brute-force approach copies all node values into an array list and indexes at k - 1. That uses O(n) auxiliary space to hold the entire tree.

Example 1 · Brute force: copy the whole inorder into a list (O(n) time, O(n) space)

KthBruteDemo.javaJava
import java.util.ArrayList;import java.util.List;
public class KthBruteDemo {    static class TreeNode {        int val;        TreeNode left, right;        TreeNode(int v) { val = v; }    }
    static void inorder(TreeNode node, List<Integer> out) {        if (node == null) return;        inorder(node.left, out);        out.add(node.val);        inorder(node.right, out);    }
    static int kthSmallest(TreeNode root, int k) {        List<Integer> values = new ArrayList<>();        inorder(root, values);        return values.get(k - 1);    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(5);        root.left = new TreeNode(3);        root.right = new TreeNode(6);        root.left.left = new TreeNode(2);        root.left.right = new TreeNode(4);        root.left.left.left = new TreeNode(1);
        System.out.println("3rd smallest: " + kthSmallest(root, 3));        System.out.println("1st smallest: " + kthSmallest(root, 1));    }}
Output
3rd smallest: 3
1st smallest: 1

What this code does

  • The whole tree is walked in inorder and every value is stored in a list; the answer is the item at position k - 1.
  • It is simple, but it always visits all n nodes and keeps n values in memory, even when k is 1.

Example 2 · Optimal: stop the inorder walk at k (O(h + k) time, O(h) space)

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static int count = 0;    static int result = -1;
    static void findKth(TreeNode node, int k) {        if (node == null || count >= k) return;        findKth(node.left, k);        count++;        if (count == k) {            result = node.val;            return;        }        findKth(node.right, k);    }
    static int kthSmallest(TreeNode root, int k) {        count = 0;        result = -1;        findKth(root, k);        return result;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(5);        root.left = new TreeNode(3);        root.right = new TreeNode(6);        root.left.left = new TreeNode(2);        root.left.right = new TreeNode(4);        root.left.left.left = new TreeNode(1);
        System.out.println("3rd smallest: " + kthSmallest(root, 3));        System.out.println("1st smallest: " + kthSmallest(root, 1));    }}
Output
3rd smallest: 3
1st smallest: 1

What this code does

  • Inorder traversal visits elements in ascending numerical sequence.
  • A counter tracks the number of visited nodes and stops upon reaching k.
  • Early return prevents exploring unnecessary subtrees after finding answer.
  • Why it is faster: the walk stops as soon as the k-th value is reached, so most of the tree is never visited and no list is built.

A better method stops traversal as soon as k nodes have been visited. Maintain a counter incremented at each inorder visit step. When the counter reaches k, record the current node value and terminate recursion immediately. Trace tree [5, 3, 6, 2, 4, null, null, 1] with k = 3. Inorder visits 1 first, then 2, then 3. At node 3, the counter equals 3, returning 3 in O(h + k) time.

Building a lazy BST iterator

A BST iterator yields elements on demand without precomputing the full list. It uses an explicit stack storing ancestor nodes along the current left spine.

Example 3 · Stack-Based BST Iterator

Main.javaJava
import java.util.Stack;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static class BSTIterator {        private Stack<TreeNode> stack = new Stack<>();
        public BSTIterator(TreeNode root) {            pushLeft(root);        }
        private void pushLeft(TreeNode node) {            while (node != null) {                stack.push(node);                node = node.left;            }        }
        public boolean hasNext() {            return !stack.isEmpty();        }
        public int next() {            TreeNode node = stack.pop();            pushLeft(node.right);            return node.val;        }    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(7);        root.left = new TreeNode(3);        root.right = new TreeNode(15);        root.right.left = new TreeNode(9);        root.right.right = new TreeNode(20);
        BSTIterator it = new BSTIterator(root);        while (it.hasNext()) {            System.out.print(it.next() + " ");        }        System.out.println();    }}
Output
3 7 9 15 20 

What this code does

  • Constructor pushes all left descendants onto an explicit stack.
  • Next pops the minimum available node and pushes left spine of right child.
  • Memory remains bounded by tree height O(h) rather than total nodes.

Initialization pushes the root and all its left descendants onto the stack. Calling next pops the top node and pushes all left descendants of its right child. Calling hasNext simply checks whether the stack is non-empty. Each node enters and leaves the stack exactly once across full iteration. Therefore next operates in O(1) amortized time while using only O(h) stack memory.

Two sum in a binary search tree

The two sum problem asks whether two nodes sum to a target value. A hash set approach records visited keys in O(n) auxiliary space.

Example 4 · Two Sum in BST using Iterators

Main.javaJava
import java.util.Stack;
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static class TreeIterator {        Stack<TreeNode> stack = new Stack<>();        boolean forward;
        TreeIterator(TreeNode root, boolean forward) {            this.forward = forward;            pushAll(root);        }
        void pushAll(TreeNode node) {            while (node != null) {                stack.push(node);                node = forward ? node.left : node.right;            }        }
        int next() {            TreeNode curr = stack.pop();            pushAll(forward ? curr.right : curr.left);            return curr.val;        }    }
    static boolean findTarget(TreeNode root, int k) {        if (root == null) return false;        TreeIterator left = new TreeIterator(root, true);        TreeIterator right = new TreeIterator(root, false);
        int i = left.next();        int j = right.next();
        while (i < j) {            int sum = i + j;            if (sum == k) return true;            if (sum < k) i = left.next();            else j = right.next();        }        return false;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(5);        root.left = new TreeNode(3);        root.right = new TreeNode(6);        root.left.left = new TreeNode(2);        root.left.right = new TreeNode(4);        root.right.right = new TreeNode(7);
        System.out.println("Pair with sum 9: " + findTarget(root, 9));        System.out.println("Pair with sum 28: " + findTarget(root, 28));    }}
Output
Pair with sum 9: true
Pair with sum 28: false

What this code does

  • One iterator advances forward while another advances backward.
  • Two pointer comparison checks pair sums without storing full arrays.
  • Achieves optimal O(n) running time with O(h) auxiliary space.

We can solve this using two pointer emulation with two BST iterators. One iterator moves forward from smallest to largest. A second reverse iterator moves backward from largest to smallest. If the sum of current values is less than target, advance the forward iterator. If the sum is greater than target, advance the reverse iterator. This achieves O(n) time while requiring only O(h) memory.

Next step

Check your understanding

10 quick questions