Skip to main content

Binary Search Tree in Java: Insert, Delete, Search, Validate BST and LCA (With Dry Runs)

Binary search tree in Java from the first rule: recursive and iterative insert and search, the three delete cases with diagrams, validating a BST with min/max bounds, kth smallest, lowest common ancestor, floor and ceiling, a balance check measured in node visits, what sorted input does to height, and ten interview problems checked against brute force. All dry runs are real program output on JDK 25.

A binary search tree in Java is about twenty lines to write and a good deal longer to get right. Insert and search come quickly; then the BST delete of a node with two children goes wrong, a validate BST function passes a tree that is not one, and sorted input quietly turns the whole structure into a linked list. This page builds the tree from the first rule, then does each operation with a diagram, a dry run printed by a real program, and the bug that usually comes with it. It complements Binary Tree Traversals in Java, which covers how to visit a tree; this one is about using the ordering to find and change things. The order here: the rule, search, insert, the three delete cases, validation, kth smallest, lowest common ancestor, floor and ceiling, height and balance, what insertion order does to cost, and ten interview problems.
Versions this was built and run against. JDK 25.0.5.1+2 (Temurin, LTS), JUnit 6.1.3 (latest GA on Maven Central), Maven 3.9.11. No other library, only java.util. All code and output below comes from the bst module of java-interview-lab; its 25 tests pass. Costs are given as counts of comparisons or node visits, not timings.

A binary search tree keeps one promise at every node

A binary tree is made of nodes, each with up to two children called left and right. A binary search tree (BST) adds one rule: for every node, all keys in its left subtree are smaller than its key, and all keys in its right subtree are larger. A subtree is a child together with everything below it. Note the word “all”: it is not just about the two direct children, and that difference is the most common wrong answer later on this page.
The sample tree used on this page503070204060803565Green: everything under the left child of 50 is smaller than 50. Amber: everything on the right is larger.The same rule holds again at 30, at 70, at 40 and at every other node.
The diagram shows the tree you get by inserting 50 30 70 20 40 60 80 35 65. Pick any node and the rule holds for everything hanging under it. In Java a node is a key and two references, from Node.java:
/** One node of a binary search tree: a key and two child links. */
public final class Node {
    public int key;
    public Node left;
    public Node right;

    public Node(int key) {
        this.key = key;
    }
}
One consequence comes free: an inorder walk (left, node, right) prints the keys in sorted order. The last line of output/01-insert-dry-run.txt shows it for this tree:
inorder: [20, 30, 35, 40, 50, 60, 65, 70, 80]
This module treats the tree as a set: inserting a key that is already there changes nothing. That is a design choice, and you should say which one you are making in an interview.

Going deeper

  • Other duplicate policies: keep a count in the node, or always send equal keys to one side. If you send them to one side, every “strictly smaller” check below has to change with it.
  • How inorder works with and without recursion: the traversals article.
  • Height on this page counts nodes on the longest root-to-leaf path, so the sample tree has height 4. Some textbooks count edges and get 3.

Search throws away a whole subtree at every step

Compare the key you want with the current node. Equal: done. Smaller: it can only be on the left. Larger: only on the right. Falling off the tree (null) means it is not there.
search(65): four nodes looked at, five never touched50307020406080356565 > 5065 < 7065 > 60At 50 go right (65 is bigger), at 70 go left, at 60 go right, at 65 stop.
The blue path in the picture is all the work there is. Here are both versions from Search.java; the loop is the recursion with the “call again” replaced by moving a variable:
public static boolean recursive(Node node, int key) {
    if (node == null) return false;
    if (key == node.key) return true;
    return recursive(key < node.key ? node.left : node.right, key);
}

public static boolean iterative(Node root, int key) {
    Node current = root;
    while (current != null && current.key != key) {
        current = key < current.key ? current.left : current.right;
    }
    return current != null;
}
The dry run for a hit and a miss, from output/02-search-dry-run.txt:
search 65:
  at 50: 65 > 50, go right
  at 70: 65 < 70, go left
  at 60: 65 > 60, go right
  at 65: equal, found after 4 nodes
search 45:
  at 50: 45 < 50, go left
  at 30: 45 > 30, go right
  at 40: 45 > 40, go right
  null reached after 3 nodes: 45 is not in the tree

min = 20 (keep going left), max = 80 (keep going right)
The cost is the number of nodes on one path, so it is at most the height h of the tree. Keep h in mind: almost every cost on this page is O(h), and the section on insertion order is about how big h can get. The loop needs O(1) extra memory, while the recursive version needs a stack frame per level.

Going deeper

  • Minimum and maximum need no comparisons with a target: keep going left, or keep going right (Search.java).
  • Binary search on an array is the same halving idea over indexes: Binary Search in Java.

Insert is a search that ends in an empty spot

To insert, search for the key. If you find it, stop. If you reach null, that empty link is exactly where the key belongs, so create a node there.
insert(35): search until you fall off, then hang the node there50307020406080356535 < 50 go left, 35 > 30 go right, 35 < 40 and 40 has no left child: 35 goes there.Existing nodes never move. A new key always arrives as a leaf.
As the diagram shows, nothing is rearranged. The recursive version in Insert.java returns the root of the subtree it was given, and the caller stores it back into its link:
/** Returns the root of the subtree after the insert. The caller MUST store the result. */
public static Node recursive(Node node, int key) {
    if (node == null) return new Node(key);
    if (key < node.key) node.left = recursive(node.left, key);
    else if (key > node.key) node.right = recursive(node.right, key);
    return node;
}
The iterative version walks down while holding the parent, because you cannot attach anything to a null reference itself (also Insert.java):
/** Same result with a loop: walk down remembering the parent, then hang the new node on it. */
public static Node iterative(Node root, int key) {
    if (root == null) return new Node(key);
    Node current = root;
    while (true) {
        if (key == current.key) return root;
        Node next = key < current.key ? current.left : current.right;
        if (next == null) {
            if (key < current.key) current.left = new Node(key);
            else current.right = new Node(key);
            return root;
        }
        current = next;
    }
}
This is the build of the sample tree, key by key, from output/01-insert-dry-run.txt:
insert 50:                    -> becomes the root
insert 30: 50 L               -> new left child of 50
insert 70: 50 R               -> new right child of 50
insert 20: 50 L, 30 L         -> new left child of 30
insert 40: 50 L, 30 R         -> new right child of 30
insert 60: 50 R, 70 L         -> new left child of 70
insert 80: 50 R, 70 R         -> new right child of 70
insert 35: 50 L, 30 R, 40 L   -> new left child of 40
insert 65: 50 R, 70 L, 60 R   -> new right child of 60
insert 40 again: no change (set semantics), still 9 nodes

Tree (recursive and iterative insert give the same outline):
50
  L: 30
     L: 20
     R: 40
        L: 35
  R: 70
     L: 60
        R: 65
     R: 80
Java passes the reference by value. Writing node = new Node(key) inside a method changes only the method’s own variable. The version below compiles, runs without error and inserts nothing. Return the node and assign it, as the correct code does.
The broken variant is kept in Mistakes.java:
/** WRONG: assigns to the parameter. Java passes the reference by value, so the caller sees nothing. */
public static void insertLost(Node node, int key) {
    if (node == null) {
        node = new Node(key);
        return;
    }
    insertLost(key < node.key ? node.left : node.right, key);
}
And the run, from output/06-mistakes.txt:
insertLost(root, 45), then search 45: false
inorder: [20, 30, 35, 40, 50, 60, 65, 70, 80]

Going deeper

BST delete has three cases, and only one needs thought

First search for the key. What happens next depends on how many children the node has. No children. Remove the link from the parent.
Case 1: delete a leaf (20)beforeafter30204035304035→The parent link becomes null. Nothing else changes.
One child. In the picture below, 65 simply takes 60’s place. This is safe because everything under 60 was already on the correct side of 70.
Case 2: delete a node with one child (60)beforeafter70608065706580→The only child moves up into the deleted node’s place, together with anything below it.
Two children. You cannot just remove the node, since two subtrees would be competing for one link. Instead, find its inorder successor: the smallest key in the right subtree. It is larger than everything on the left and smaller than everything else on the right, so it can legally stand where the deleted key stood.
Case 3: delete a node with two children (50)beforeafter5030702040608035656030702040658035→Copy the successor (60, the smallest key on the right) into the node.Then delete the old 60, which has no left child, so it is case 1 or case 2.
The successor was found by going left as far as possible, so it has no left child. Removing it is therefore always one of the two easy cases. All three fit in one method in Delete.java:
/** Returns the root of the subtree after the delete. The caller MUST store the result. */
public static Node recursive(Node node, int key) {
    if (node == null) return null;
    if (key < node.key) {
        node.left = recursive(node.left, key);
    } else if (key > node.key) {
        node.right = recursive(node.right, key);
    } else {
        if (node.left == null) return node.right;   // leaf (returns null) or only a right child
        if (node.right == null) return node.left;   // only a left child
        Node successor = Search.min(node.right);    // two children: smallest key on the right
        node.key = successor.key;
        node.right = recursive(node.right, successor.key);
    }
    return node;
}
Note that the first if inside the else covers two cases at once: for a leaf, node.right is null, and returning it removes the leaf. Case 1, from output/03-delete-leaf.txt:
delete 20:
  at 50: 20 < 50, go left
  at 30: 20 < 30, go left
  at 20: equal, found after 3 nodes
  leaf: return null to the parent

after:
50
  L: 30
     R: 40
        L: 35
  R: 70
     L: 60
        R: 65
     R: 80

inorder: [30, 35, 40, 50, 60, 65, 70, 80]
Case 2, from output/04-delete-one-child.txt:
delete 60:
  at 50: 60 > 50, go right
  at 70: 60 < 70, go left
  at 60: equal, found after 3 nodes
  one child (65): return that child to the parent

after:
50
  L: 30
     L: 20
     R: 40
        L: 35
  R: 70
     L: 65
     R: 80

inorder: [20, 30, 35, 40, 50, 65, 70, 80]
Case 3 on the root, from output/05-delete-two-children.txt:
delete 50:
  at 50: equal, found after 1 nodes
  two children: successor = smallest key in right subtree = 60
  copy 60 into the node, then delete 60 from the right subtree

after:
60
  L: 30
     L: 20
     R: 40
        L: 35
  R: 70
     L: 65
     R: 80

inorder: [20, 30, 35, 40, 60, 65, 70, 80]
Two ways to break delete. Copying the successor up and forgetting to delete it leaves the key in the tree twice. Calling delete and ignoring the returned root does nothing visible when the node being removed is the root and has fewer than two children.
Both were run; the transcript is output/06-mistakes.txt:
tree 50,70: Delete.recursive(root, 50) with the result thrown away
  inorder from the old root variable: [50, 70]
  root = Delete.recursive(root, 50): [70]

deleteLeavesDuplicate(sample, 50)
  inorder: [20, 30, 35, 40, 60, 60, 65, 70, 80]
  isBst: false
Iterative delete, which relinks the successor node instead of copying its key Copying the key is short, but it means a Node object that someone else holds a reference to now carries a different key, and with a key-value node you must copy the value too. Relinking avoids that. From Delete.java:
/** The same three cases with loops. It relinks the successor node instead of copying its key. */
public static Node iterative(Node root, int key) {
    Node parent = null;
    Node target = root;
    while (target != null && target.key != key) {
        parent = target;
        target = key < target.key ? target.left : target.right;
    }
    if (target == null) return root;

    Node replacement;
    if (target.left == null) {
        replacement = target.right;
    } else if (target.right == null) {
        replacement = target.left;
    } else {
        Node successorParent = target;
        Node successor = target.right;
        while (successor.left != null) {
            successorParent = successor;
            successor = successor.left;
        }
        if (successorParent != target) {
            successorParent.left = successor.right;
            successor.right = target.right;
        }
        successor.left = target.left;
        replacement = successor;
    }
    if (parent == null) return replacement;
    if (parent.left == target) parent.left = replacement;
    else parent.right = replacement;
    return root;
}
The fiddly part is the successor that is deeper than the immediate right child: its own right subtree has to be handed to its old parent before it adopts the deleted node’s children.

Going deeper

  • You can use the predecessor (largest key on the left) instead of the successor. Either is correct; the resulting shapes differ.
  • The JDK does the copy-the-successor step too: in JDK 25, TreeMap.deleteEntry copies the successor’s key and value into a node with two children and then removes the successor node instead, repairing the red-black colouring as part of that removal (TreeMap Javadoc; the source is in the JDK’s lib/src.zip).
  • Both delete versions are checked against java.util.TreeSet in output/15-random-operations.txt.

Validate BST by passing a range down, not by checking children

The tempting solution checks that each left child is smaller and each right child larger. It is wrong, because the rule is about whole subtrees.
Every parent–child pair looks fine, but this is not a BST50307020556080(-inf, +inf)(-inf, 50)(50, +inf)allowed (30, 50)55 is bigger than its parent 30, as a right child should be. It is also bigger than 50, and it sits left of 50.The allowed range, narrowed at every step down, catches it.
The picture is the counterexample. The fix is to carry a lower and an upper bound down the tree: going left makes the current key the new upper bound, going right makes it the new lower bound. The wrong check and the right one sit side by side in Validate.java:
/** WRONG: compares each node only with its two direct children. */
public static boolean childrenOnly(Node node) {
    if (node == null) return true;
    if (node.left != null && node.left.key >= node.key) return false;
    if (node.right != null && node.right.key <= node.key) return false;
    return childrenOnly(node.left) && childrenOnly(node.right);
}

/** Correct: every node must lie strictly between the bounds set by ALL its ancestors. */
public static boolean isBst(Node root) {
    return within(root, null, null);
}

private static boolean within(Node node, Integer low, Integer high) {
    if (node == null) return true;
    if (low != null && node.key <= low) return false;
    if (high != null && node.key >= high) return false;
    return within(node.left, low, node.key) && within(node.right, node.key, high);
}
Running both on that tree, from output/07-validate.txt:
childrenOnly: true
isBst:        false
byInorder:    false   inorder = [20, 30, 55, 50, 60, 70, 80]

Bounds trace (stops at the first violation):
  node 50  allowed (-inf, +inf)  ok
  node 30  allowed (-inf, 50)  ok
  node 20  allowed (-inf, 30)  ok
  node 55  allowed (30, 50)  VIOLATION
Do not use Integer.MIN_VALUE and MAX_VALUE as “no bound”. They are legal keys. With int sentinels and strict comparisons, a one-node tree holding either of them is reported as invalid. Use null (an Integer parameter) or widen to long.
The last two lines of output/07-validate.txt show it:
single node 2147483647: intSentinels=false  isBst=true
single node -2147483648: intSentinels=false  isBst=true
Validation has to look at every node, so it is O(n) time with O(h) stack. How often does the wrong version get away with it? Over 20,000 random small binary trees, it wrongly accepted 417 that a literal check of the definition rejects, while both correct versions agreed with the definition on every tree (output/16-ten-problems.txt, line 1).
The other correct method: inorder must be strictly increasing Walk inorder with an explicit stack and compare each key with the previous one. It stops at the first drop and needs no bounds. From Validate.java:
/** Correct: inorder must be strictly increasing. */
public static boolean byInorder(Node root) {
    var stack = new java.util.ArrayDeque<Node>();
    Node current = root;
    Integer previous = null;
    while (current != null || !stack.isEmpty()) {
        while (current != null) {
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        if (previous != null && current.key <= previous) return false;
        previous = current.key;
        current = current.right;
    }
    return true;
}

Going deeper

  • With duplicates allowed on one side, exactly one of the two comparisons in within becomes non-strict.
  • The brute-force definition used as the referee is isBstByDefinition in Trees.java.

The kth smallest key is the kth stop of an inorder walk

Since inorder produces sorted order, the kth smallest key is the kth node that walk visits. There is no need to build a list of all keys: use an explicit stack and stop early. From Queries.java:
/** k is 1-based. Iterative inorder that stops at the k-th key: O(h + k). */
public static int kthSmallest(Node root, int k) {
    if (k < 1) throw new IllegalArgumentException("k must be at least 1");
    var stack = new ArrayDeque<Node>();
    Node current = root;
    while (current != null || !stack.isEmpty()) {
        while (current != null) {
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        if (--k == 0) return current.key;
        current = current.right;
    }
    throw new NoSuchElementException("the tree has fewer than k keys");
}
The stack holds the nodes you passed on the way left and still have to come back to. For k = 4 on the sample tree, from output/08-kth-smallest.txt:
push 50   stack (top first) [50]
push 30   stack (top first) [30, 50]
push 20   stack (top first) [20, 30, 50]
pop  20   stack (top first) [30, 50]   k left 3
pop  30   stack (top first) [50]   k left 2
push 40   stack (top first) [40, 50]
push 35   stack (top first) [35, 40, 50]
pop  35   stack (top first) [40, 50]   k left 1
pop  40   stack (top first) [50]   k left 0

answer: 40
The cost is O(h + k): down one path, then k pops. If the kth smallest is asked often on a tree that also changes, store the size of each subtree in its node. Then compare k with the left subtree’s size and go straight down one path in O(h), at the price of keeping the sizes correct in every insert and delete. That variant is not in the module.

Going deeper

The lowest common ancestor is where two search paths split

The lowest common ancestor (LCA) of two nodes is the deepest node that has both of them in its subtree (a node counts as its own ancestor). In an ordinary binary tree you have to search both sides. In a BST, start at the root: while both keys are smaller, go left; while both are larger, go right. The first node where that stops being true is the answer.
lca(60, 65) and lca(35, 65): the answer is where the paths split503070204060803565lca(35, 65) = 50 (amber): 35 goes left there, 65 goes right.lca(60, 65) = 60 (green): one of the two keys is the node itself.
Both outcomes in the picture come from the same loop in Queries.java:
/** Lowest common ancestor. Assumes p and q are both in the tree. */
public static Node lca(Node root, int p, int q) {
    Node current = root;
    while (current != null) {
        if (p < current.key && q < current.key) current = current.left;
        else if (p > current.key && q > current.key) current = current.right;
        else return current;
    }
    return null;
}
The traces, from output/09-lca.txt:
lca(20, 35):
  at 50: both smaller, go left
  at 30: paths split here, answer 30
lca(35, 65):
  at 50: paths split here, answer 50
lca(60, 65):
  at 50: both larger, go right
  at 70: both smaller, go left
  at 60: paths split here, answer 60

lca(20, 99), with 99 absent, returns 50 (a wrong-looking answer: check presence first)
This LCA assumes both keys exist. The last line of the trace asks about a key that is not in the tree and gets 50 back without complaint. If that is possible in your problem, run two searches first; it is still O(h).

Going deeper

  • The 18,990 random pairs in output/16-ten-problems.txt are checked against the obvious method: record both paths from the root and take the last node they share.
  • For a binary tree that is not a search tree, the usual answer is a postorder recursion that returns the node when one target is found on each side. It is O(n).

Floor and ceiling find the nearest key when yours is missing

floor(x) is the largest key that is ≤ x. ceiling(x) is the smallest key that is ≥ x. Search for x as usual, and on the way remember the best candidate seen.
floor(45): remember the last time you turned right503070204060803565At 50: too big, go left. At 30: candidate, go right. At 40: a better candidate, go right.Nothing is there, so floor(45) = 40. ceiling(45) = 50, the last place we turned left.
In the floor search, a node smaller than x is a candidate, and anything better must be to its right. Ceiling is the mirror. Both are in Queries.java; here is floor:
/** Largest key less than or equal to x. */
public static OptionalInt floor(Node root, int x) {
    OptionalInt best = OptionalInt.empty();
    Node current = root;
    while (current != null) {
        if (current.key == x) return OptionalInt.of(x);
        if (current.key < x) {
            best = OptionalInt.of(current.key);     // a candidate; a bigger one may be to the right
            current = current.right;
        } else {
            current = current.left;
        }
    }
    return best;
}
Both traces for x = 45, from output/10-floor-ceiling.txt:
floor(45):
  at 50: too big, best = none, go left
  at 30: candidate, best = 30, go right
  at 40: candidate, best = 40, go right
  answer 40
ceiling(45):
  at 50: candidate, best = 50, go left
  at 30: too small, best = 50, go right
  at 40: too small, best = 50, go right
  answer 50

floor(10) = OptionalInt.empty, ceiling(90) = OptionalInt.empty
The return type is OptionalInt because there may be no answer, and no int is free to mean “none”.

Going deeper

Height is one recursion; the balance check is where visits pile up

The height of a tree is 1 plus the height of its taller child, and 0 for an empty tree. A tree is height-balanced when, at every node, the two subtree heights differ by at most 1. The direct translation asks for both heights at each node, which measures the same subtrees again and again. The better version computes height once, in postorder, and returns −1 as soon as something below is unbalanced. From Balance.java (the Counter only counts visits):
public static int height(Node node) {
    if (node == null) return 0;
    return 1 + Math.max(height(node.left), height(node.right));
}

/**
 * Asks for the height again at every node: O(n log n) on a balanced tree. Because it returns at the
 * first failure, a plain chain costs only about n; the bad shapes are balanced near the top only.
 */
public static boolean isBalancedTopDown(Node node, Counter c) {
    if (node == null) return true;
    if (Math.abs(countedHeight(node.left, c) - countedHeight(node.right, c)) > 1) return false;
    return isBalancedTopDown(node.left, c) && isBalancedTopDown(node.right, c);
}

private static int countedHeight(Node node, Counter c) {
    if (node == null) return 0;
    c.visits++;
    return 1 + Math.max(countedHeight(node.left, c), countedHeight(node.right, c));
}

/** One postorder pass; -1 means "already unbalanced below here": O(n). */
public static boolean isBalanced(Node root, Counter c) {
    return check(root, c) >= 0;
}

private static int check(Node node, Counter c) {
    if (node == null) return 0;
    c.visits++;
    int left = check(node.left, c);
    if (left < 0) return -1;
    int right = check(node.right, c);
    if (right < 0 || Math.abs(left - right) > 1) return -1;
    return 1 + Math.max(left, right);
}
Node visits for both, from output/13-balance-visits.txt:
sample tree: height 4, balanced true

tree                        balanced     top-down     one pass
perfect, n = 1023               true         8194         1023
perfect, n = 16383              true       196610        16383
chain, n = 1000                false          999         1000
chain, n = 2000                false         1999         2000
comb 100, n = 5050             false       171603          106
comb 200, n = 20100            false      1353203          206
comb 400, n = 80200            false     10746403          406
“The top-down check is O(n²) on a skewed tree” is not true of this code. Because it returns at the first failing node, a plain chain fails at the root after n − 1 visits, one fewer than the one-pass version. Its bad inputs are trees that look balanced along a long path and fail only deep down.
The “comb” rows are such a shape: a spine where each node has another comb on the left and a plain chain of the same height on the right. Four times the nodes costs the top-down check about eight times the visits, while the one-pass version stays in the hundreds. The shape is built in ShapeTest.java. On a perfectly balanced tree the top-down check is O(n log n): 196,610 visits for 16,383 nodes against 16,383.

Going deeper

  • The O(n²) claim does hold for a diameter computed by calling height at every node, because that code has no early exit; the counts are in the traversals article.
  • Without the early return (for example, computing the children’s results into variables before testing the current node) the top-down version loses its shortcut on chains.

Insertion order decides whether the tree is fast at all

Every O(h) above depends on the height, and a plain BST does nothing to control it. Insert keys that are already sorted and every new key goes to the right of the last one.
The same seven keys, two insertion orders12345674261357insert 1,2,3,4,5,6,7insert 4,2,6,1,3,5,7Left: height 7, a linked list in disguise. Right: height 3. The ordering rule is satisfied by both,so nothing in a plain BST pushes it towards the good one.
Measured on 1023 keys, same set, different order (output/11-insertion-order.txt, produced by ShapeTest.java):
order                         height   avg nodes per search
sorted 1..1023                  1023                 512.00
shuffled, seed 1                  24                  11.58
shuffled, seed 2                  19                  11.47
shuffled, seed 3                  20                  11.81
shuffled, seed 4                  23                  12.15
shuffled, seed 5                  25                  12.98
middle-first (fromSorted)         10                   9.01
Random order gives a height of two to two and a half times the best possible here, and searches that look at 11 to 13 nodes. Sorted order gives 512 on average. Sorted input is not exotic: database ids and timestamps arrive that way. A deep tree also breaks recursion. DeepTreeDemo.java links a 100,000-node chain and searches it on a thread with a 512 KB stack (output/14-deep-chain.txt); the depth at which this happens depends on the stack size and the JVM:
chain of 100000 nodes, 512 KB thread stack
Search.recursive: threw java.lang.StackOverflowError
Search.iterative: returned true
Self-balancing trees (AVL, red-black) restore the shape with rotations during insert and delete. You rarely need to write one: TreeMap and TreeSet are red-black trees. Feeding them sorted keys and counting calls to the comparator gives (output/12-treeset-sorted-input.txt):
n = 1023    contains(): worst 18 comparisons, average 9.51   (plain BST on the same input: worst 1023, average 512.0)
n = 100000  contains(): worst 31 comparisons, average 16.10   (plain BST on the same input: worst 100000, average 50000.5)

Going deeper

  • The TreeMap Javadoc promises log(n) time for containsKey, get, put and remove.
  • If all the keys are known up front, you do not need rotations: sort them and build from the middle (problem 5 below).

Complexity table

n is the number of nodes and h the height: about log n when the tree is balanced, n when it is a chain.
OperationTime (balanced)Time (worst, chain)Extra space
search, insert, deleteO(log n)O(n)O(1) iterative, O(h) recursive
min, max, floor, ceiling, successorO(log n)O(n)O(1)
lowest common ancestorO(log n)O(n)O(1)
kth smallest (stack)O(log n + k)O(n)O(h)
validate, height, inorderO(n)O(n)O(h)
balance check, one passO(n)O(n)O(h)
balance check, top-down with early returnO(n log n)about n on a chain; far more on the comb aboveO(h)
build by inserting n keysO(n log n)O(n²) for sorted inputO(n) for the tree
Keys inserted in random order give an expected height of order log n, which is why textbooks quote O(log n) as the average. It is an average over insertion orders, not a guarantee about yours.

Ten binary search tree interview problems, each checked against brute force

Nearly all of them reduce to two ideas from above: follow one path and discard the rest, or inorder is sorted.
#ProblemIdeaTime
1Validate BSTbounds passed downO(n)
2Kth smallestinorder, stop earlyO(h + k)
3Lowest common ancestorfirst splitO(h)
4Range sumprune subtreesO(h + m), m keys in range
5Sorted array to balanced BSTmiddle as rootO(n)
6Inorder successorlast left turnO(h)
7Two keys summing to targetwalk plus HashSetO(n) expected
8Minimum differenceinorder neighboursO(n)
9Recover two swapped keysfind the drops in inorderO(n)
10Trim to a rangeprune and relinkO(n)
Problems 1 to 3 are solved in the sections above. For each of the ten, CrossCheckTest.java generates seeded random trees and compares the answer with a slow method that ignores the ordering rule (sort all keys, try all pairs, compare root paths). The summary, from output/16-ten-problems.txt:
 1. validate BST: 20000 random binary trees, 7382 were BSTs; bounds and inorder agreed on all; childrenOnly wrongly accepted 417
 2. kth smallest: 27427 (tree, k) cases against sorting all keys
 3. lowest common ancestor: 18990 pairs against comparing the two root paths
 4. range sum: 2000 cases against filtering all keys; sample tree [35, 50] = 125
 5. sorted array to balanced BST: every n from 0 to 500 is a balanced BST of minimum height with the same keys
 6. inorder successor: 2000 cases against scanning all keys; successor(40) in the sample tree = 50
 7. two keys summing to a target: 2000 cases (359 true) against all pairs
 8. minimum difference: 1729 trees against all pairs; MIN_VALUE and MAX_VALUE give 4294967295 (needs long)
 9. recover two swapped keys: 1834 damaged trees, all restored
10. trim to a range: 2000 cases against filtering all keys, result still a BST; sample trimmed to [35, 65] = [35, 40, 50, 60, 65]
Problem 4: sum of keys in a range If a node is below the range, its whole left subtree is too, so go only right; and the mirror. From Problems.java:
/** 4. Sum of the keys in [low, high]. Subtrees that cannot overlap the range are never entered. */
public static long rangeSum(Node node, int low, int high) {
    if (node == null) return 0;
    if (node.key < low) return rangeSum(node.right, low, high);
    if (node.key > high) return rangeSum(node.left, low, high);
    return node.key + rangeSum(node.left, low, high) + rangeSum(node.right, low, high);
}
Dry run for [35, 50] on the sample tree: 50 is inside (add 50). On the left, 30 is below the range, so only its right side is entered, where 40 and 35 are added. On the right, 70 and 60 are above the range, so only their left links are followed, down to null. Total 50 + 40 + 35 = 125.
Problem 5: sorted array to a balanced BST Make the middle element the root and recurse on each half. From Problems.java:
/** 5. Height-balanced tree from a strictly increasing array: the middle element is the root. */
public static Node fromSorted(int[] sorted) {
    return fromSorted(sorted, 0, sorted.length - 1);
}

private static Node fromSorted(int[] a, int lo, int hi) {
    if (lo > hi) return null;
    int mid = lo + (hi - lo) / 2;
    Node node = new Node(a[mid]);
    node.left = fromSorted(a, lo, mid - 1);
    node.right = fromSorted(a, mid + 1, hi);
    return node;
}
For 1 2 3 4 5 6 7 the roots chosen are 4, then 2 and 6, then the four leaves.
Problem 6: inorder successor of a value It is ceiling with “strictly greater”. From Problems.java:
/** 6. Inorder successor: the smallest key strictly greater than x. */
public static OptionalInt successor(Node root, int x) {
    OptionalInt best = OptionalInt.empty();
    Node current = root;
    while (current != null) {
        if (current.key > x) {
            best = OptionalInt.of(current.key);
            current = current.left;
        } else {
            current = current.right;
        }
    }
    return best;
}
Dry run for 40: at 50, a candidate, go left; at 30, not greater, go right; at 40, not greater, go right; null. Answer 50.
Problem 7: two keys that add up to a target Walk the tree once and keep a set of keys already seen. The sum is done in long. From Problems.java:
/** 7. Are there two different nodes whose keys add up to target? One walk plus a HashSet. */
public static boolean hasPairWithSum(Node root, long target) {
    return pair(root, target, new HashSet<>());
}

private static boolean pair(Node node, long target, Set<Long> seen) {
    if (node == null) return false;
    if (pair(node.left, target, seen)) return true;
    if (seen.contains(target - node.key)) return true;
    seen.add((long) node.key);
    return pair(node.right, target, seen);
}
This works on any binary tree. The BST-specific alternative runs two stack iterators, one ascending and one descending, and needs O(h) space instead of O(n).
Problem 8: minimum difference between two keys In sorted order the closest pair is always a pair of neighbours. Subtract in long, or two extreme keys overflow. From Problems.java:
/** 8. Minimum difference between any two keys: only inorder neighbours can win. Needs 2+ nodes. */
public static long minDifference(Node root) {
    var stack = new ArrayDeque<Node>();
    Node current = root;
    Node previous = null;
    long best = Long.MAX_VALUE;
    while (current != null || !stack.isEmpty()) {
        while (current != null) {
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        if (previous != null) best = Math.min(best, (long) current.key - previous.key);
        previous = current;
        current = current.right;
    }
    return best;
}
Problem 9: recover a BST with two swapped keys In inorder, a swap shows up as one or two places where the sequence drops. Take the larger element of the first drop and the smaller element of the last. For 20 30 35 40 50 with 30 and 50 swapped the walk reads 20 50 35 40 30: the first drop is 50 → 35, the last is 40 → 30, so swap 50 and 30. From Problems.java:
/** 9. Exactly two keys of a BST were exchanged. Find them in the inorder walk and swap them back. */
public static void recoverSwapped(Node root) {
    var stack = new ArrayDeque<Node>();
    Node current = root;
    Node previous = null;
    Node first = null;
    Node second = null;
    while (current != null || !stack.isEmpty()) {
        while (current != null) {
            stack.push(current);
            current = current.left;
        }
        current = stack.pop();
        if (previous != null && previous.key > current.key) {
            if (first == null) first = previous;    // the big one of the first drop
            second = current;                       // the small one of the last drop
        }
        previous = current;
        current = current.right;
    }
    if (first != null) {
        int t = first.key;
        first.key = second.key;
        second.key = t;
    }
}
Problem 10: trim a BST to a range The same pruning as range sum, but returning the new subtree root. From Problems.java:
/** 10. Remove every key outside [low, high], keeping the shape of what survives. */
public static Node trim(Node node, int low, int high) {
    if (node == null) return null;
    if (node.key < low) return trim(node.right, low, high);
    if (node.key > high) return trim(node.left, low, high);
    node.left = trim(node.left, low, high);
    node.right = trim(node.right, low, high);
    return node;
}

Going deeper

  • Random testing found no disagreement; that is evidence, not a proof. The generators use small trees on purpose, because small trees hit the edge cases often.
  • Interview preparation beyond trees: the Java interview preparation guide.

Exam-style questions with answers

Q1. Insert 15, 10, 20, 8, 12, 25 into an empty BST. What is the inorder output? 8 10 12 15 20 25. Inorder of a BST is the sorted order, whatever the insertion order was.
Q2. From the sample tree, delete 30 using the successor. What replaces it? 35, the smallest key in the right subtree of 30 (go right to 40, then left to 35). 35 is a leaf, so removing the old copy is case 1.
Q3. Can a preorder listing alone rebuild a BST? Yes, when keys are distinct. Inserting the keys in preorder order reproduces the same shape, because every parent appears before its children. A plain binary tree needs more than one traversal.
Q4. Why can a BST not be validated by comparing each node with its two children? The rule covers whole subtrees. In the tree on this page, 55 is a correct right child of 30 and still sits in the left subtree of 50.
Q5. What is the height of the tree after inserting 1 to n in order? n (counting nodes). Each key becomes the right child of the previous one. For n = 1023 the measured average successful search visits 512 nodes (output/11-insertion-order.txt).

Should you write your own BST in production?

Usually not. For a sorted set or map use TreeSet or TreeMap: balanced, with floor, ceiling and range views built in. If you only need membership tests, HashSet is the simpler tool. If the data is fixed, a sorted array with binary search is smaller and easier. Write a BST to learn it, to answer an interview, or when you need extra data per subtree (sizes, sums, intervals) that the JDK classes do not let you attach, and in that case use a balancing scheme.

Further reading

No Comments yet!

This site uses Akismet to reduce spam. Learn how your comment data is processed.