Trees· 15 min

BST Insert

Insert values maintaining the BST property

Setup

Step 1 / 28

Current step

1 / 28

Starting with an empty BST. We'll insert each value one by one.

Step log

Tree is empty — insert values to begin.
Current / on path
Just inserted
Found
bst_insert.java
1Node insert(Node root, int value) {
2 if (root == null) return new Node(value);
3 if (value < root.value)
4 root.left = insert(root.left, value);
5 else if (value > root.value)
6 root.right = insert(root.right, value);
7 return root;
8}
● Java

BST Insert

Each value descends left if smaller than the current node, right if larger, until it finds an empty slot. Duplicate values are skipped.

Nodes
7
Mode
insert
Time (avg)
O(log n)
Time (worst)
O(n)
50307020406080