cswork / templatesOpen the Line 500 list

STOP 13 · LISTS & TREES

Binary Search Trees

Iterative inorder walks a BST in sorted order O(h + k) time · O(h) space

Contest ratings Rating 1335–Rating 1335· median Rating 1335(1 of 15 problems rated by zerotrac)

Open the Line 500 list · stop 13 · 15 problems
Learn first
Leads to
No later stop builds on it.
How often asked
asked by 7 companies · in 11 reportsAmazon 3, Meta 3, Microsoft 1, Pinduoduo 1, Salesforce 1

Warm up with this one

LC 700Search in a Binary Search TreeEasy
Stuck? Peek at the approach

Use value ordering to search only one subtree.

Key points

  1. An inorder walk of a BST is sorted, so k-th smallest, validation and predecessor/successor all become inorder problems.
  2. To validate a BST, pass (lo, hi) bounds down; every node must sit strictly inside the range its ancestors allow.
  3. Search and insert follow a single path, O(h): O(log n) when balanced and O(n) on a chain.

Common pitfalls

  • Comparing a node only with its children misses a small value deep in the right subtree.
  • Using INT_MIN/INT_MAX as bounds fails when a node holds that exact value; use long or null for "unbounded".
  • Forgetting to move to node.right in the iterative walk repeats nodes or stops early.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

Binary search tree · find, insert, delete

Run find(6), insert(5), delete(1), delete(14), delete(8)

Try your own input
831647101413
CurrentDiscovered / computedAnswer
Operation
—
Comparisons
0
In-order
1 3 4 6 7 8 10 13 14

Inserting 8, 3, 10, 1, 6, 14, 4, 7, 13 in order gives this binary search tree: everything left of a node is smaller, everything right is bigger, so the in-order walk is sorted.

InvariantAt every node, keys in the left subtree are smaller and keys in the right subtree are bigger.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 700, with it.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right


def kth_smallest(root, k: int) -> int:
    """1-indexed; assumes 1 <= k <= number of nodes."""
    stack, node = [], root
    while True:
        while node:  # go as far left as possible
            stack.append(node)
            node = node.left
        node = stack.pop()  # the next value in sorted order
        k -= 1
        if k == 0:
            return node.val
        node = node.right
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// 1-indexed; assumes 1 <= k <= number of nodes.
int kthSmallest(TreeNode* root, int k) {
    stack<TreeNode*> st;
    TreeNode* node = root;
    while (true) {
        for (; node; node = node->left) st.push(node);  // go as far left as possible
        node = st.top();  // the next value in sorted order
        st.pop();
        if (--k == 0) return node->val;
        node = node->right;
    }
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // 1-indexed; assumes 1 <= k <= number of nodes.
    int kthSmallest(TreeNode root, int k) {
        Deque<TreeNode> st = new ArrayDeque<>();
        TreeNode node = root;
        while (true) {
            for (; node != null; node = node.left) st.push(node); // go as far left as possible
            node = st.pop(); // the next value in sorted order
            if (--k == 0) return node.val;
            node = node.right;
        }
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// kthSmallest is 1-indexed and assumes 1 <= k <= number of nodes.
func kthSmallest(root *TreeNode, k int) int {
	var st []*TreeNode
	node := root
	for {
		for ; node != nil; node = node.Left { // go as far left as possible
			st = append(st, node)
		}
		node = st[len(st)-1] // the next value in sorted order
		st = st[:len(st)-1]
		k--
		if k == 0 {
			return node.Val
		}
		node = node.Right
	}
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Bounds recursion: each node inside the range its ancestors setO(n) time · O(h) recursion depth

Comparing with the parent is not enough (a small value deep in a right subtree breaks the rule too): pass an open range (lo, hi) down, tightening the upper bound to the current value on the left and the lower bound on the right. LC 98 (Validate Binary Search Tree); start from long or infinite bounds in case a node holds the int extremes.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def is_valid_bst(root) -> bool:
    """Every node lies strictly inside the bounds its ancestors set (LC 98)."""

    def ok(node, lo, hi) -> bool:  # node.val must be in the open range (lo, hi)
        if not node:
            return True
        if not lo < node.val < hi:
            return False
        return ok(node.left, lo, node.val) and ok(node.right, node.val, hi)

    return ok(root, float("-inf"), float("inf"))
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// Every node lies strictly inside the bounds its ancestors set (LC 98).
bool isValidBst(TreeNode* root) {
    function<bool(TreeNode*, long long, long long)> ok = [&](TreeNode* node, long long lo, long long hi) {
        if (!node) return true;  // node->val must be in the open range (lo, hi)
        if (node->val <= lo || node->val >= hi) return false;
        return ok(node->left, lo, node->val) && ok(node->right, node->val, hi);
    };
    return ok(root, LLONG_MIN, LLONG_MAX);
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // Every node lies strictly inside the bounds its ancestors set (LC 98).
    boolean isValidBst(TreeNode root) {
        return ok(root, Long.MIN_VALUE, Long.MAX_VALUE);
    }

    // node.val must be in the open range (lo, hi).
    private boolean ok(TreeNode node, long lo, long hi) {
        if (node == null) return true;
        if (node.val <= lo || node.val >= hi) return false;
        return ok(node.left, lo, node.val) && ok(node.right, node.val, hi);
    }
}
Go
import "math"

type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// isValidBst reports whether every node lies strictly inside the bounds its ancestors set (LC 98).
func isValidBst(root *TreeNode) bool {
	var ok func(node *TreeNode, lo, hi int) bool // node.Val must be in the open range (lo, hi)
	ok = func(node *TreeNode, lo, hi int) bool {
		if node == nil {
			return true
		}
		if node.Val <= lo || node.Val >= hi {
			return false
		}
		return ok(node.Left, lo, node.Val) && ok(node.Right, node.Val, hi)
	}
	return ok(root, math.MinInt, math.MaxInt)
}
Delete a node: swap in the inorder successor when it has two childrenO(h) time · O(h) recursion depth

For deleting from or trimming a BST (LC 450, Delete Node in a BST; LC 669, Trim a BST): recurse to one side by value and return the new subtree root for the parent to reattach. A node with at most one child is replaced by that child; with two, copy the smallest value of its right subtree (the inorder successor) and delete that value from the right subtree.

Python
class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val, self.left, self.right = val, left, right

def delete_node(root, key: int):
    """The BST without key, if it was there (LC 450)."""
    if not root:
        return None
    if key < root.val:
        root.left = delete_node(root.left, key)
    elif key > root.val:
        root.right = delete_node(root.right, key)
    else:
        if not root.left or not root.right:  # zero or one child: lift it up
            return root.left or root.right
        succ = root.right  # two children: take the inorder successor's value...
        while succ.left:
            succ = succ.left
        root.val = succ.val
        root.right = delete_node(root.right, succ.val)  # ...and delete it below
    return root
C++
struct TreeNode {
    int val;
    TreeNode *left, *right;
    TreeNode(int v, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(v), left(l), right(r) {}
};

// The BST without key, if it was there (LC 450).
TreeNode* deleteNode(TreeNode* root, int key) {
    if (!root) return nullptr;
    if (key < root->val) root->left = deleteNode(root->left, key);
    else if (key > root->val) root->right = deleteNode(root->right, key);
    else {
        if (!root->left || !root->right) return root->left ? root->left : root->right;  // zero or one child: lift it up
        TreeNode* succ = root->right;  // two children: take the inorder successor's value...
        while (succ->left) succ = succ->left;
        root->val = succ->val;
        root->right = deleteNode(root->right, succ->val);  // ...and delete it below
    }
    return root;
}
Java
class TreeNode {
    int val;
    TreeNode left, right;

    TreeNode(int val) {
        this.val = val;
    }

    TreeNode(int val, TreeNode left, TreeNode right) {
        this.val = val;
        this.left = left;
        this.right = right;
    }
}

class Solution {
    // The BST without key, if it was there (LC 450).
    TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) return null;
        if (key < root.val) root.left = deleteNode(root.left, key);
        else if (key > root.val) root.right = deleteNode(root.right, key);
        else {
            if (root.left == null || root.right == null) return root.left != null ? root.left : root.right; // lift the only child
            TreeNode succ = root.right; // two children: take the inorder successor's value...
            while (succ.left != null) succ = succ.left;
            root.val = succ.val;
            root.right = deleteNode(root.right, succ.val); // ...and delete it below
        }
        return root;
    }
}
Go
type TreeNode struct {
	Val         int
	Left, Right *TreeNode
}

// deleteNode returns the BST without key, if it was there (LC 450).
func deleteNode(root *TreeNode, key int) *TreeNode {
	if root == nil {
		return nil
	}
	switch {
	case key < root.Val:
		root.Left = deleteNode(root.Left, key)
	case key > root.Val:
		root.Right = deleteNode(root.Right, key)
	default:
		if root.Left == nil { // zero or one child: lift it up
			return root.Right
		}
		if root.Right == nil {
			return root.Left
		}
		succ := root.Right // two children: take the inorder successor's value...
		for succ.Left != nil {
			succ = succ.Left
		}
		root.Val = succ.Val
		root.Right = deleteNode(root.Right, succ.Val) // ...and delete it below
	}
	return root
}

Why it works

  1. Why inorder is sorted: at every node, inorder emits the whole left subtree (all smaller), then the node, then the right subtree (all larger); by induction on subtrees, the sequence is strictly increasing.
  2. Comparing with the parent alone is not enough: a whole subtree must fit the range its ancestors allow, so pass (lo, hi) bounds down. In [5, 1, 6, null, null, 3, 7], 3 is smaller than its parent 6 but sits in 5's right subtree, so the tree is invalid.
  3. Search goes to one side at each step because the other subtree cannot contain the target, so it follows a single path in O(h).

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
二叉搜索树最有用的性质是中序遍历有序,因为每个节点都是先输出更小的左子树、再输出自己、再输出更大的右子树。所以第 k 小、验证 BST、找前驱后继,我都转成中序遍历,用栈迭代可以在第 k 个时提前停下。验证时不能只和父节点比,要把上下界一路传下去。查找和插入只走一条路径,O(h)。
English
The most useful BST fact is that an inorder walk is sorted, since every node emits its smaller left subtree, then itself, then its larger right subtree. So I turn k-th smallest, validation and predecessor or successor into inorder walks, and an iterative walk with a stack can stop as soon as it reaches the k-th node. To validate, I pass lower and upper bounds down instead of comparing with the parent only. Search and insert follow a single path, which is O(h).

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

5 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

5 questions
  1. Why is checking left child < node < right child at every node not enough to validate a binary search tree?
  2. Inserting 1, 2, …, n in order into a plain (unbalanced) binary search tree gives what height, in edges?
  3. How do you delete a node with two children from a BST?
  4. This is a plain, unbalanced binary search tree. What is the total time of the loop?
    def insert(node, key):
        if not node:
            return Node(key)
        if key < node.key:
            node.left = insert(node.left, key)
        else:
            node.right = insert(node.right, key)
        return node
    
    root = None
    for k in range(n):
        root = insert(root, k)
  5. next() is called n times to walk a BST with n nodes and height h in order. What does each next() cost?
    class InorderIter:
        def __init__(self, root):
            self.stack = []
            self._push_left(root)
    
        def _push_left(self, node):
            while node:
                self.stack.append(node)
                node = node.left
    
        def next(self):
            node = self.stack.pop()
            self._push_left(node.right)
            return node.key

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        node = node.right

Practice by stage

This stop's 15 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 4

#ProblemApproachRating
700Search in a Binary Search TreeUse value ordering to search only one subtree.
701Insert into a Binary Search TreeInsert a new node while preserving the BST ordering property.
108Convert Sorted Array to Binary Search TreeRecursively split a sorted array at its midpoint to construct a height-balanced BST.
938Range Sum of BSTPrune by the requested BST range to avoid subtrees that must lie outside it.Rating 1335

Core 8

#ProblemApproachRating
98Validate Binary Search TreeValidate a BST with bounds inherited from ancestors instead of checking only direct parent-child pairs.
230Kth Smallest Element in a BSTUse sorted inorder traversal to find the kth smallest element and stop as soon as it is found.
530Minimum Absolute Difference in BSTCompare adjacent inorder values, handling zero values, predecessor initialization, and minimum-difference updates.
235Lowest Common Ancestor of a Binary Search TreeLocate the BST common ancestor from the relationship between both target values and the current root.
285Inorder Successor in BST 🔒Find the inorder successor, distinguishing a right-subtree minimum from a larger ancestor.
450Delete Node in a BSTDelete a BST node by handling the cases of zero, one, and two children separately.
669Trim a Binary Search TreeTrim a BST to a value range, retaining valid subtrees even when their root is removed.
538Convert BST to Greater TreeAccumulate larger values in reverse inorder, showing how traversal direction determines the running state.

Advanced 3

#ProblemApproachRating
109Convert Sorted List to Binary Search TreeConvert a sorted list to a balanced BST and compare repeated midpoint searches with inorder simulation.
99Recover Binary Search TreeIdentify two swapped nodes through inorder inversions, covering adjacent and nonadjacent swaps.
426Convert Binary Search Tree to Sorted Doubly Linked List 🔒Convert a BST in place into a sorted circular doubly linked list while maintaining both directions and the head-tail connection.