What makes a tree a BST

Video lessonComing soon

1 Binary search that can grow

A problem keeps a set of numbers. New values keep arriving, and between them it asks whether some value is there. A sorted array answers each question with binary search in about 17 steps. But each new value must go in its place, and every bigger value shifts right. Over 10⁵ arrivals, that can be around 5 × 10⁹ steps, and it gets Time Limit Exceeded (TLE). A linked list adds a value without shifting, but every search walks it from the start.

A binary search tree (BST) gets both. It is a binary tree in which each node splits the values: smaller ones go in its left subtree, bigger ones in its right. Here are the nine values of our running example, sorted and as a BST:

200301352403454505606707808
Sorted
203035404550607080
The same values as a BST

The root, 50, plays the part of binary search's first middle value. Each child splits its own side again. So a search throws away one side at every node, and a new value becomes a new leaf, with nothing shifted. The values are distinct unless a problem says otherwise.

2 Each node owns a range

Here is the rule exactly. For every node, every value in its left subtree is smaller than the node, and every value in its right subtree is bigger. Comparing a node with its two children is not enough.

The number line shows why. The root 50 cuts the line in two: its left subtree lives below 50, and its right subtree above. Each node further down cuts its own piece again.

Follow the path to 45. It went left at 50, so 45 is below 50. It went right at 30 and at 40, so it is above 40. So 45 must lie between 40 and 50. This is its allowed range, written (40, 50). Every node above it on the path helps set it, not just the parent.

203035404550607080
The path to 45
405045
45 must lie between 40 and 50

Now change 45 to 55:

203035404550607080
A BST
203035405550607080
Not a BST: 55 sits left of 50

In the second tree, every parent and child look fine: 55 is bigger than its parent 40. But 55 is in the left subtree of 50, where every value must be below 50. Its range is still (40, 50), and 55 falls outside it. A search for 55 would turn right at 50 and never find it. This is the classic trap, and we call this tree the trap tree.

3 Inorder reads the values sorted

Inorder writes the left subtree, then the node, then the right subtree. In a BST, the left subtree holds only smaller values and the right only bigger ones. So each node comes after everything smaller in its subtree and before everything bigger. The same holds inside each subtree, so the whole list comes out sorted.

Our drawings give each node its own column, so a BST reads sorted from left to right. In the trap tree, 55 stands left of 50, and its inorder shows the break:

200301352403454505606707808
Inorder of the BST: sorted
200301352403554505606707808
Inorder of the trap tree: 55 before 50

The other direction holds too: a binary tree whose inorder is strictly increasing is a BST. Two facts follow:

  • Smallest and largest. The smallest value is the leftmost node: keep going left until there is no left child. The largest is the rightmost.
  • The kth smallest. It is the kth value the inorder walk writes, so the walk can stop there.

5 Validating: pass the range down

To check a tree, we check every node against its allowed range. The root's range is (−∞, +∞). A node with range (low, high) hands each child a range:

  • The left child gets (low, node's value). It must stay below the node.
  • The right child gets (node's value, high). It must stay above the node.

Each child keeps one bound and takes the parent's value as the other, so the range narrows on the way down. This is the passing-down style from the recursion lessons. Here it is on the trap tree:

Checking the trap tree
203035405550607080
50
50: any value fits

The same run as a trace table:

nodelowhighinside?
50−∞+∞yes
30−∞50yes
20−∞30yes
403050yes
353040yes
554050no

The walk stops at the first node outside its range, so 70, 60 and 80 are never checked. On the real BST, 45 passes in the last row.

C++

Bounds wider than int. A node can hold INT_MAX itself, so INT_MAX cannot stand for "no bound". long long bounds start outside every int, and LLONG_MIN comes from <climits>.

Bounds wider than int. A node can hold Integer.MAX_VALUE itself, so it cannot stand for "no bound". long bounds start outside every int.

Infinity as the open bound. float("inf") compares correctly with any integer, so the root's range needs no special case.

Infinity as the open bound. -Infinity and Infinity compare correctly with any number, so the root's range needs no special case.

int is 64 bits. Node values fit in 32 bits, so math.MinInt64 and math.MaxInt64 lie outside every one of them.

i64 bounds. Each value becomes an i64 before the compare, so i64::MIN and i64::MAX lie outside every i32 node.

Bounds wider than int. A node can hold int.MaxValue itself, so it cannot stand for "no bound". long bounds start outside every int.

Every tab returns true on our BST and false on the trap tree. Each node is checked once, so the time is O(n). The call stack holds one path, so the extra space is O(h).

Section 3 gives a second way: walk inorder and check that each value is bigger than the one before. This is also O(n). The previous value starts as "none", not as the smallest int, for the reason in section 8.

6 Insert and delete

Insert. A new value goes where a search for it fails. The search for 65 ended at 60's empty right child. That spot's range is (60, 70), and 65 fits it. So 65 becomes a new leaf there, and nothing else moves:

203035404550607080
The search for 65 ends right of 60
20303540455060657080
65 is a new leaf

A recursive insert returns the root of the subtree it was given, and the parent stores it: node.left = insert(node.left, val). That assignment attaches the new leaf.

Delete. What happens depends on how many children the node has:

  • No children. Remove the leaf. Its parent's pointer becomes null.
  • One child. The child takes the node's place, with its whole subtree.
  • Two children. We copy in the node's inorder successor, the smallest value in its right subtree: go right once, then left until there is no left child. It is bigger than the whole left side and smaller than the rest of the right side, so it fits. Then we delete the successor from the right subtree. It has no left child, so that is case one or two.

Deleting 30 from our tree is the third case. Its successor is 35:

203035404550607080
Delete 30. Its successor is 35
2035404550607080
35 moves up, and its old leaf goes

7 The height decides the cost

Most operations walk one path, so their cost is the height h:

OperationTimeExtra space
Search, floor, ceilO(h)O(1) as a loop
Insert, deleteO(h)O(h) if recursive
Validate, inorderO(n)O(h)

The shape depends on the order of the inserts. In sorted order, each new value goes right of the last one, and the tree becomes a chain:

1020304050
Inserted 30, 20, 40, 10, 50
1020304050
Inserted 10, 20, 30, 40, 50
Tree of 10⁵ nodesHeightOne search
Balancedabout 17about 17 steps
Chain10⁵up to 10⁵ steps

A chain is a linked list again. Inserting 10⁵ sorted values walks the whole chain each time, around 5 × 10⁹ steps, and that gets TLE.

Balanced BSTs fix this. AVL trees and red-black trees turn a few nodes around after each insert or delete, so the height stays near log n. Interviews rarely ask us to write one. The ordered sets and maps in most standard libraries are balanced trees, and they answer search, insert, delete, floor and ceil in O(log n):

C++

set and map are red-black trees. s.lower_bound(x) points to the smallest value ≥ x, the ceil. For the floor, take s.upper_bound(x) and step back once, unless it is s.begin().

TreeSet and TreeMap are red-black trees. set.floor(x) and set.ceiling(x) return the nearest values, or null when there is none. A TreeMap has floorKey and ceilingKey.

No ordered set is built in. A sorted list with bisect finds the floor and ceil in O(log n), but each insert shifts values, which is O(n).

No ordered set is built in. A sorted array with the binary search loop finds the floor and ceil, but each insert shifts values, which is O(n).

No ordered set is built in. A sorted slice with sort.SearchInts finds the floor and ceil, but each insert shifts values, which is O(n).

BTreeSet and BTreeMap. These are B-trees, which keep several values in each node, but they give the same ordered operations. set.range(..=x).next_back() is the floor, and set.range(x..).next() is the ceil.

SortedSet and SortedDictionary are red-black trees. set.GetViewBetween(int.MinValue, x) holds the values up to x, and its Max is the floor when its Count is above 0. A view from x to int.MaxValue gives the ceil as its Min.

When a problem builds a BST from a sorted array, the middle value as the root keeps it balanced. Each half then builds its subtree the same way.

8 Mistakes, and when to use a BST

  • Comparing only with the children. This check returns true on the trap tree.
  • int limits as "no bound". With INT_MAX as the root's upper bound, the tree [2147483647] fails val >= high. An inorder check with prev starting at INT_MIN fails [-2147483648] the same way. Use a wider type, infinity or "none".
  • Equal values. LeetCode's rule is strict, so [7, 7], a 7 with a left child 7, is not a BST. A check that lets an equal value through gets Wrong Answer. A problem that allows duplicates picks a side for them, or keeps a count in each node.
  • Not reattaching. A recursive insert that calls insert(node.left, val) and drops the result loses the new leaf. A recursive delete has the same trap.

The sign is a question about a BST: search, the smallest or largest value, or the nearest value to x. Three moves cover most of them:

  • Walk one path to search, insert, or find a floor or ceil.
  • Skip a whole subtree when its range lies outside the question. A sum over the values from 30 to 60 never needs 20 or 80.
  • Walk inorder when the order matters: the kth smallest, a check that the tree is valid, or two values with a given sum.
At each node of a BST, ask which side the answer can be on. The other side never needs a look.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.