Skip to lesson

Inserting into a binary search tree preserves ordering by placing new nodes at leaf positions.

Recursive insertion into a binary search tree

Insertion finds the correct position where the new value belongs. If the tree is empty, create a new root node containing the value. Otherwise compare the value with the current node value.

Inserting 4

Step 1 of 5

5372
new
4
Insert 4 into this tree. Start the comparison at the root, value 5.

Example 1 · Recursive BST Insertion

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static TreeNode insert(TreeNode root, int val) {        if (root == null) {            return new TreeNode(val);        }        if (val < root.val) {            root.left = insert(root.left, val);        } else if (val > root.val) {            root.right = insert(root.right, val);        }        return root;    }
    static void printInorder(TreeNode root) {        if (root == null) return;        printInorder(root.left);        System.out.print(root.val + " ");        printInorder(root.right);    }
    public static void main(String[] args) {        TreeNode root = null;        int[] values = {5, 3, 7, 2, 4, 8};        for (int v : values) {            root = insert(root, v);        }        printInorder(root);        System.out.println();    }}
Output
2 3 4 5 7 8 

What this code does

  • Base case creates and returns a new node when null is reached.
  • Recursive calls reassign child pointers to return updated subtrees.
  • Inorder traversal verifies that inserted keys stay sorted.

If the value is smaller, recurse into the left subtree. If the value is larger, recurse into the right subtree. When a null reference is reached, attach the new node there. Trace inserting value 4 into a tree with root 5 and left child 2. Start at 5. Since 4 is less than 5, move left to 2. At node 2, since 4 is greater than 2, move right. The right child of 2 is null, so attach new node 4 there.

Order of execution

Order of an insertion

Tap the steps in the order insertion runs them.

Iterative insertion and duplicate policies

Iterative insertion avoids recursion stack overhead using a pointer loop. A parent pointer tracks the last non-null node while descending. Once the loop finds a null spot, attach the new child to parent.

Example 2 · Iterative BST Insertion

Main.javaJava
public class Main {    static class TreeNode {        int val;        TreeNode left;        TreeNode right;        TreeNode(int val) { this.val = val; }    }
    static TreeNode insertIterative(TreeNode root, int val) {        if (root == null) return new TreeNode(val);        TreeNode curr = root;        TreeNode parent = null;
        while (curr != null) {            parent = curr;            if (val < curr.val) {                curr = curr.left;            } else if (val > curr.val) {                curr = curr.right;            } else {                return root; // ignore duplicate            }        }
        if (val < parent.val) {            parent.left = new TreeNode(val);        } else {            parent.right = new TreeNode(val);        }        return root;    }
    public static void main(String[] args) {        TreeNode root = new TreeNode(10);        insertIterative(root, 5);        insertIterative(root, 15);        insertIterative(root, 12);
        System.out.println("Root: " + root.val);        System.out.println("Right: " + root.right.val);        System.out.println("Right-left: " + root.right.left.val);    }}
Output
Root: 10
Right: 15
Right-left: 12

What this code does

  • The parent reference remembers the last visited node before hitting null.
  • A comparison attaches the new node to either parent left or right.
  • Duplicate keys are ignored without modifying tree structure.

Example 3 · BST with Duplicate Frequency Counters

Main.javaJava
public class Main {    static class Node {        int val;        int count;        Node left;        Node right;        Node(int val) {            this.val = val;            this.count = 1;        }    }
    static Node insertWithCount(Node root, int val) {        if (root == null) return new Node(val);        if (val == root.val) {            root.count++;        } else if (val < root.val) {            root.left = insertWithCount(root.left, val);        } else {            root.right = insertWithCount(root.right, val);        }        return root;    }
    public static void main(String[] args) {        Node root = null;        int[] items = {4, 2, 4, 6, 4};        for (int x : items) {            root = insertWithCount(root, x);        }        System.out.println("Value 4 count: " + root.count);        System.out.println("Value 2 count: " + root.left.count);    }}
Output
Value 4 count: 3
Value 2 count: 1

What this code does

  • Nodes store a count field to represent duplicate frequencies.
  • Encountering an existing value increments its frequency counter.
  • Tree height remains minimal by preventing duplicate nodes.

Real-world applications must choose a policy for duplicate keys. One policy ignores duplicates, preserving unique sets like TreeSet. Another policy increments a count field on the existing node. A third policy consistently routes duplicate keys into right subtrees.

Fix the error

Fix the compile error

Read the real compiler error, then pick the line that fixes it.

The recursive insert must attach a node, not a number.

public class InsertFix {
static class Node { int val; Node left, right; Node(int v) { val = v; } }
static Node insert(Node root, int val) {
if (root == null) return new Node(val);
if (val < root.val) root.left = insert(root.left, val);
else root.right = val;
return root;
}
public static void main(String[] args) {
Node root = insert(null, 5);
insert(root, 3);
System.out.println(root.left.val);
}
}

Error

InsertFix.java:6: error: incompatible types: int cannot be converted to Node
        else root.right = val;
                          ^

Building a tree from a list of values

Building a BST inserts values one by one into an initially empty tree. Inserting n values into a balanced tree takes O(n log n) total time.

Java
int[] values = {8, 3, 10, 1, 6};TreeNode root = null;             // start with an empty treefor (int v : values) {    root = insert(root, v);       // O(h) for each insert}// Sorted input {1, 2, 3, 4, 5} makes every node a right child: a chain of height 4

However, insertion order determines the resulting tree shape. If values arrive in sorted order, each node attaches as a right child. This creates a completely skewed tree with O(n squared) total construction cost.

Next step

Check your understanding

10 quick questions