Binary search tree: smaller on the left, bigger on the right

Put values into nodes and hang them in a tree. Every node keeps one rule: everything below on the left is smaller than me, and everything below on the right is bigger. Then any search is just "smaller, go left; bigger, go right" from the root down.

Short answer. A binary search tree is a tree where, at every node, the whole left branch is smaller and the whole right branch is bigger. Search, insert, and delete walk down one level per comparison, so they take as many steps as the tree is tall. Insert values in a shuffled order and the height stays close to log n, which is fast. Insert them in sorted order and the tree becomes one long line that takes n steps, like a list. Reading left, me, right gives the values in sorted order, so the tree is good at range searches and walking in order.

How to read it: orange with a "here" arrow = current node · thick orange arrow with a sign (5 < 8) = where the walk goes after comparing · light green = path so far · green = found · blue = new node · blue dashed = empty spot for the new node · orange dashed = node to delete · purple = smallest on the right · purple arrow = a value moves · faint dashed = node a value left

Type a value (a whole number from 0 to 99) and press a button. That makes a list of steps, and "Next" walks through it one step at a time. The tree changes to the final result as soon as you press the button, so the next button starts from the new tree. The starting tree is 8, 3, 10, 1, 6, 14, 4, 7 inserted in that order, the same as the hand example in section 2. The tree holds up to 20 values.

Try this. (1) Search for 5: it compares with 8, 3, 6, and 4, finds the right side of 4 empty, and stops with "not there" (4 comparisons). (2) Now Insert 5: the same four comparisons, then 5 goes into that empty spot (right of 4). Where a search stops is exactly where an insert goes. (3) From the starting tree, delete 1: it is a leaf, so it is just cut off (5 steps). Delete 10: its child 14 moves up (4 steps). Delete 3: it has two children, so the walk goes to the right child 6 and then left to the end, 4, picks 4, moves it into the place of 3 (purple arrow), and then cuts off the node 4 left (7 steps). In every case the left, me, right line under the picture stays sorted.

Definitions

The sections below explain with pictures and experiments. The textbook definitions are these. A node x of the tree has one key x.key and a left and a right child, and n is the number of nodes. This page assumes all keys are different (a key that is already there is not inserted again).

binary search tree
A tree in which every node has at most two children and, at every node x, the inequality below holds for every node y in the left subtree of x and every node z in the right subtree of x. The condition is about the whole subtree, not only the children.

y.key<x.key<z.key

height, depth
This page counts levels. The depth of a node is the number of the level it is on, counting the root as level 1, and the height h of the tree is the depth of its deepest node, that is, the number of levels (some books count links instead, which gives one less. The red-black tree page counts that way). Search, insert and delete make at most h comparisons. The lowest height you can build with n nodes is:

hmin=⌈log2(n+1)⌉

in-order traversal
A way to visit every node once: at each node, do an in-order traversal of the left subtree, visit the node, then do an in-order traversal of the right subtree. An in-order traversal of a binary search tree gives the keys from smallest to largest.
successor
The successor of node x is the node with the smallest key among the keys bigger than x.key. If x has a right subtree, it is the node with the smallest key in that subtree, that is, the node you reach by going to the right child and then left as far as you can. It takes the place of a node with two children when that node is deleted.
degenerate tree
A tree in which every node has at most one child. Its n nodes form one line, so the height is n, and searching becomes the same as scanning a list from the front. Inserting in sorted order makes this shape.

1. The rule: everything left is smaller, everything right is bigger

A node holds one value and two links to its children (left and right). Call the top node the root, a node with no children a leaf, and a node together with everything under it that node's branch. In a binary search tree every node keeps this rule:

values in the left branch  <  me  <  values in the right branch     (at every node)

The key word is branch: not just the left child, but everything under it on the left is smaller. So once you go right at some node, every value you meet after that is bigger than that node. That is why each comparison throws away one whole side of what is left. It is the same idea as binary search, which compares with the middle of a sorted array and drops half, but stored in linked nodes instead of an array.

PropertyIn plain wordsIn the demo
Search, insert, delete take as long as the heightEach comparison goes down one level. The number of steps is at most the number of levelsThe step count in the first demo
Where a search stops is where an insert goesA search for a missing value stops at an empty spot, and insert hangs the new node there. No other node movesTry this (1) and (2)
Reading left, me, right gives a sorted lineAs long as the rule holds, the smallest always comes firstThe line under the first demo
The insert order decides the shapeSame values, different order, different height. Sorted order makes one lineThe two buttons in the second demo
The smallest value is at the far leftGo left from the root until you cannot. The biggest is at the far rightDelete with two children

2. Follow it by hand

Insert 8, 3, 10, 1, 6, 14, 4, 7 into an empty tree in that order. Each value starts at the root, goes left if smaller and right if bigger, and hangs in the first empty spot it reaches.

ValueComparisons on the way (smaller, left; bigger, right)Where it hangs (first empty spot)
8(empty tree)root
33 < 8 → leftleft of 8
1010 > 8 → rightright of 8
11 < 8 → left, 1 < 3 → leftleft of 3
66 < 8 → left, 6 > 3 → rightright of 3
1414 > 8 → right, 14 > 10 → rightright of 10
44 < 8 → left, 4 > 3 → right, 4 < 6 → leftleft of 6
77 < 8 → left, 7 > 3 → right, 7 > 6 → rightright of 6

The result has 4 levels: 8 on level 1, 3 and 10 on level 2, 1, 6, and 14 on level 3, and 4 and 7 on level 4.

31647 4167 delete smallest on right moved from ① ② ③ before after
Deleting 3, which has two children. (1) Go down to the right child 6, and (2) go left to the end: 4, the smallest value in the right branch. (3) Write 4 into the place of 3, then cut off the node 4 left (faint dashed ring).

The number of comparisons to find a value equals the level it sits on. For these eight values the average is (1×1 + 2×2 + 3×3 + 4×2) ÷ 8 = 22 ÷ 8 = 2.75.

3. Walk left, me, right and you get a sorted line

At every node, read the whole left branch, then me, then the whole right branch (in-order traversal). By the rule, the left branch is all smaller and the right branch is all bigger, so I always come right after the smaller ones and right before the bigger ones. The same happens inside every branch, so the whole tree comes out smallest first. The tree from section 2 reads 1, 3, 4, 6, 7, 8, 10, 14.

This makes questions like "the smallest", "the value right after 7", or "every value from 4 to 9" easy. Finding the start of a range takes as many steps as the height, and then one step per value you take out. A hash table stores keys in mixed-up order, so to answer these it has to take everything out and sort it.

4. Search, insert, and delete take as long as the tree is tall

All three walk down from the root one level per comparison. The two-children delete just walks a bit further down. So the time grows with the height of the tree (the number of levels). The same n values can make trees of very different heights.

Number of values nLowest possible tree (1, 2, 4, … per level)Stretched into one line
154 levels15 levels
1,000,00020 levels (2²⁰ = 1,048,576, so 20 levels fit them all)1,000,000 levels

The lowest height is log₂(n + 1) rounded up. Double n and you add just one level (O(log n)). A line doubles the steps when n doubles (O(n)). The source shows that for a tree built from a shuffled order, the average number of comparisons for a search grows like log n. Try changing only the order in the demo below.

The values are 1 to n (7 to 15 of them). "Insert shuffled" mixes them with a fixed-seed random generator, so the order is the same every time you open the page. The average search is the average number of comparisons to find each value in the tree.

Try this. (1) At the start (15 values, shuffled) the height is 6 levels and the average search is 3.87 comparisons. That is a bit taller than the lowest possible 4 levels (a full 4-level tree averages 49 ÷ 15 ≈ 3.27). (2) Press "Insert smallest first, in order". Every value hangs on the right of the one before, giving 15 levels and an average of 8. Finding the last value, 15, takes 15 comparisons, the same as scanning a list from the front. (3) Set the count to 7: shuffled gives 3 levels (the lowest possible) and an average of 2.43, while in order gives 7 levels and an average of 4. (4) Set it to 11: even the shuffled tree is 8 levels tall. Shuffling usually keeps the tree low, but not always.

To stop leaving the shape to luck, use a balanced tree that turns nodes on every insert and delete to keep the height near log n. The next page, red-black tree, shows one way.

5. Which one to use when

O(1) is a few steps no matter what n is. O(log n) is one more step when n doubles. O(n) doubles when n doubles. O(n log n) is a bit more than that. n is the number of stored values, and k is the number of values you take out.

ChoiceSearch (best · usual · worst)Insert · deleteRange search · walk in orderExtra memoryUse it when
Binary search tree (this page)O(1) at the root · O(log n) inserted in shuffled order · O(n) as one lineSame as searchGood. O(height + k)Two child links per valueLearning. Or when you can trust the insert order to be mixed up
Balanced treeO(1) · O(log n) · O(log n)O(log n), even at worstGood. O(log n + k)Two links plus one color mark per nodeAn ordered dictionary that keeps changing for a long time
Hash tableO(1) · O(1) · O(n) when everything lands in one slotUsually O(1)Bad. Take everything out and sort, O(n log n)A table with empty slots left on purposeYou only ever look up exact keys
Sorted array + binary searchO(1) · O(log n) · O(log n)O(n). Everything after it shifts by oneGood. O(log n + k)NoneYou build it once and rarely change it

6. Real code

class Node:
    def __init__(self, key):
        self.key, self.left, self.right = key, None, None

def insert(node, key):                  # returns the root after inserting
    if node is None:
        return Node(key)
    if key < node.key:
        node.left = insert(node.left, key)
    elif key > node.key:
        node.right = insert(node.right, key)
    return node

def inorder(node):                      # left, me, right
    return inorder(node.left) + [node.key] + inorder(node.right) if node else []

root = None
for key in [8, 3, 10, 1, 6, 14, 4, 7]:
    root = insert(root, key)
print(inorder(root))                    # [1, 3, 4, 6, 7, 8, 10, 14]

Python's standard library has no such tree. The closest is a sorted list with bisect: bisect.insort(values, 5). Search is O(log n), but insert is O(n) because the values after it shift (the fourth row of the table above).

Where it is used

Common questions

What happens if I insert the same value twice?

It is up to you. The demo on this page does nothing when the value is already there. The code in the source is a dictionary of key and value pairs, so the same key does not make a new node; it only replaces the value. To keep repeated values, pick one side for ties (for example "equal goes right"), or keep a count in each node.

When deleting, can I use the biggest value on the left instead?

Yes. The biggest value in the left branch is the largest value smaller than the node you delete, so putting it there keeps the rule: everything on the left is smaller and everything on the right is bigger. This page and the source use the smallest value on the right.

Why is this plain tree rarely used as is in real code?

Because the insert order can stretch it into one long line. If values arrive already sorted, like numbers that keep going up, a search takes n steps, just like a list. So real code uses a balanced tree (a red-black tree, for example) that reshapes itself on every insert and delete to keep the height near log n.

Words

Word used hereTextbook term
A tree with smaller on the left, bigger on the rightbinary search tree (BST)
The top node · a node with no childrenroot · leaf
A node and everything under it, a branchsubtree
Number of levels · which level a node is onheight · depth. Some books count links instead of levels, which gives one less
Walking left, me, rightin-order traversal
The smallest value in the right branchsuccessor
Deleting a two-children node by swapping in its successorHibbard deletion
Range searchrange search, range query
A tree stretched into one linedegenerate tree
A tree that keeps its height near log nbalanced BST

Sources

← Hash tablesRed-black trees →