Binary trees & BSTs

A binary tree gives every node two children. Keep smaller values on the left and larger ones on the right, and finding a value takes one step per level instead of one per item.

3 examples13 to practiceRead · 6 min
The idea

A binary tree gives each node at most two children

A binary tree is built from nodes, like a linked list, but each node has two references instead of one: left and right. Either can be nothing. One node, the root, is where everything starts; every other node hangs below exactly one parent. A node with no children is a leaf.

8310161447

Eight nodes on four levels; each arrow is a left or a right reference. The node 3, with 1, 6, 4 and 7 below it, is the left subtree of 8.

A node together with everything below it is a subtree. Every node's left child starts its left subtree and its right child starts its right subtree, so most tree code is recursive: do something at this node, then hand each subtree to the same function.

In the pseudocode, TreeNode(x) makes a node holding x whose left and right are nothing.

The order

A search tree keeps smaller values on the left and larger ones on the right

A binary search tree (BST) is a binary tree with one rule about where values go. The tree above follows it: 8's left subtree holds 1, 3, 4, 6 and 7, all smaller than 8, and its right subtree holds 10 and 14, both larger. The same is true at 3, at 6 and at every other node.

The rule

At every node of a binary search tree, every value in the left subtree is smaller and every value in the right subtree is larger. Not just the children: the whole subtree.

That rule is binary search, built into the shape. Comparing with one node tells you which half of the remaining values can hold the one you want, and the other half is never looked at. Read the nodes from left to right and they come out sorted.

Search

Each comparison chooses one subtree and discards the other

To find 7, compare it with the root. Smaller goes left, larger goes right, equal means found. Running off the tree into nothing means the value isn't there.

Four comparisons for a tree of eight values. The work is one step per level, so the cost is O(h), where h is the number of levels.

Insert

A new value goes where a search for it falls off the tree

Inserting is a search that is expected to fail. Walk down exactly as if looking for the new value; when the next step would go to nothing, that empty spot is the only place the value can go without breaking the rule. Hang a new node there. No existing node moves.

The new value always ends up as a leaf. That is also why the order of inserts decides the shape: the first value inserted stays the root for good.

Hard

Deleting a node with two children borrows the next larger value

Deleting a leaf is easy: its parent forgets it. A node with one child is nearly as easy: the child moves up into its place. A node with two children is the hard case, because two subtrees can't both hang from its parent's one slot.

The fix: find the next larger value in the tree, the leftmost node of the right subtree, and copy it over the value being deleted. Everything on the left is still smaller, and everything that remains on the right is still larger. The node the value came from has no left child, so removing it is one of the easy cases.

The recursion returns each subtree's new top, and every caller stores it back with node.left ← … or node.right ← …. That one habit handles all three cases, including deleting the root.

The cost

The shape decides the cost, and the insert order decides the shape

Search, insert and delete each follow one path from the root, so all three are O(h). How big h is depends entirely on the order the values arrived in:

Inserted in this order

Shape

Levels

4, 2, 6, 1, 3, 5, 7

Bushy: every level full

3

1, 2, 3, 4, 5, 6, 7

A chain: every node has only a right child

7

A full tree with 20 levels holds 2²⁰ − 1 = 1,048,575 values, so a million values can fit in 20 levels, and every operation costs about 20 comparisons. Insert the same million values in sorted order and the tree is a chain a million levels deep: every operation is a linear search. Sorted input is common in practice, so a plain search tree is a risk. Balanced trees keeps the tree bushy whatever the order.

Check yourself

4 questions

1. At node 6 of a binary search tree, which values can its right subtree hold?
2. Where does a newly inserted value end up?
3. You insert 10, 20, 30, 40 and 50, in that order, into an empty binary search tree. How many levels does it have?
4. Deleting a node with two children copies which value into it?
Takeaways

Remember this

  • A binary tree gives every node a left and a right reference; a node and everything below it form a subtree.
  • A binary search tree keeps every value in a left subtree smaller and every value in a right subtree larger, at every node.
  • Search, insert and delete each follow one path down: O(h), where h is the number of levels.
  • A two-child delete copies the next larger value up and deletes that value lower down, which is an easy case.
  • Sorted inserts turn a plain search tree into a chain, so h can be n.
Practice

Now solve some yourself

Only this topic 0 of 8 solved

  1. Easy
    How many levels deep is the tree?
    Binary trees & BSTs
  2. Easy
    Mirror a tree left to right
    Binary trees & BSTs
  3. Easy
    Are two trees identical?
    Binary trees & BSTs
  4. Easy
    Is the tree its own mirror image?
    Binary trees & BSTs
  5. Easy
    A path from the root down to a leaf with a given sum
    Binary trees & BSTs
  6. Easy
    Add up the values that fall in a range
    Binary trees & BSTs
  7. Medium
    Is it really a search tree?
    Binary trees & BSTs
  8. Medium
    Cut a search tree down to a range of values
    Binary trees & BSTs

Mixed with topics you have practiced 0 unlocked

    5 more once you have practiced Tree traversals, Balanced trees. Play one of its examples to the end and solve one of its problems to unlock them.

    Problems open on their own sites (LeetCode, Codeforces, CodeChef, AtCoder, CSES) in a new tab. Tick Solved when you get it accepted there; your ticks decide which mixed problems open next.

    Next

    Tree traversals

    Continue