Data structures

Binary trees, visualized.

A node with two pointers instead of one. Keep smaller values on the left and bigger ones on the right, and in a well-shaped tree finding anything takes a few hops, not a long walk.

What is a binary tree?

A binary tree is made of nodes, like a linked list, but each node has two pointers: left and right. The node at the very top is the root. The nodes a node points at are its children. A node with no children is a leaf. A node’s depth is how many steps it is below the root.

A binary search tree (BST) adds one rule, everywhere in the tree: every value on a node’s left side is smaller than it, and every value on its right side is bigger. That rule tells you which way to go at every node, so in a balanced tree each step skips about half of what is left.

depth 0depth 1depth 283101614← rootleafleafleafchildren of 8
Each box is [left | value | right]. Left of 8: 3, 1, 6, all smaller. Right of 8: 10, 14, all bigger.

01 — one item first

Binary search tree insertion: start with one insert.

Build a tree one value at a time. At every node the new value asks one question: am I smaller (go left) or bigger (go right)?

Python

class Node:
def __init__(self, value):
self.value = value
self.left = None # smaller values
self.right = None # bigger values
def insert(root, value):
if root is None:
return Node(value) # empty: new root
cur = root
while True:
if value < cur.value: # smaller: go left
if cur.left is None:
cur.left = Node(value)
return root
cur = cur.left
elif value > cur.value: # bigger: go right
if cur.right is None:
cur.right = Node(value)
return root
cur = cur.right
else:
return root # already there

02 — why bother

Find 7: list vs tree.

The same fifteen numbers, twice. A sorted linked list can only walk from the front. A search tree throws away half of what is left at every step.

Sorted linked list

looks: 0

Binary search tree

looks: 0

Press a button to search both at once.

03 — your turn

Insert and search.

Type a number. The ghost starts at the root and compares at every node. Count the comparisons: that is the cost.

Pick a value and press insert or search.

Python

class Node:
def __init__(self, value):
self.value = value
self.left = None # smaller values
self.right = None # bigger values
def insert(root, value):
if root is None:
return Node(value) # empty: new root
cur = root
while True:
if value < cur.value: # smaller: go left
if cur.left is None:
cur.left = Node(value)
return root
cur = cur.left
elif value > cur.value: # bigger: go right
if cur.right is None:
cur.right = Node(value)
return root
cur = cur.right
else:
return root # already there
Each operation ends with its cost here.

04 — visit every node

Tree traversals: inorder, preorder, postorder and level order.

A list has one order. A tree has several, depending on when you print a node: before its children, between them, after them, or level by level.

printed:

Python

def in_order(node):
if node is None:
return
in_order(node.left)
print(node.value) # between the sides
in_order(node.right)

05 — taking one out

Delete from a binary search tree, three ways.

Removing a node must keep the rule (smaller left, bigger right) true. A leaf just goes. A node with one child hands its place to that child. A node with two children needs a stand-in.

Pick a case. Each one starts from the same tree.

Python

def delete(node, value):
if node is None:
return None # not in the tree
if value < node.value:
node.left = delete(node.left, value)
elif value > node.value:
node.right = delete(node.right, value)
else: # found it
if node.left is None:
return node.right # leaf, or right child only
if node.right is None:
return node.left # left child only
succ = node.right # two children: the smallest
while succ.left is not None: # value on the right
succ = succ.left
node.value = succ.value # copy it up
node.right = delete(node.right, succ.value)
return node

06 — the classic bug

Sorted input breaks the tree.

Insert values that are already in order, and every new value is bigger than everything before it, so it always goes right. The “tree” is a linked list leaning sideways.

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

looks: –

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

looks: –

Same seven values, two insert orders. Press the button to build both.

07 — spot them in the wild

Tree or not?

A tree has one root, and every other item has exactly one parent. No loops, no item with two parents. Decide for each, then read why.

Folders and files on your computer

A company org chart

Friends on a social network

Autocomplete as you type a word

A database index that finds a row by its id

The undo history in a text editor

The HTML of a web page

A music playlist played in order

08 — the boss level

Validate a binary search tree.

A classic interview question. Checking each parent against its children is not enough: a value deep down must also respect every ancestor above it. The trick: pass an allowed range down the tree.

Python

from math import inf
def is_valid(node, low=-inf, high=inf):
if node is None:
return True # an empty spot is fine
if not (low < node.value < high):
return False # outside its range
return (is_valid(node.left, low, node.value)
and is_valid(node.right, node.value, high))
Time O(n): each node is checked once. Memory O(h): one waiting call per level of the tree.

09 — cheat sheet

Binary search tree time complexity.

Everything costs one step per level, so it all depends on the height. A balanced tree with n nodes is about log₂ n levels tall (20 levels for a million). A lopsided one can be n levels tall.

JobBalancedLopsided (sorted input)
Search, insert, deleteO(log n)O(n)a walk down a list
Smallest / largest valueO(log n)keep going left / rightO(n)
All values in sorted orderO(n)in-order walkO(n)
MemoryO(n)two pointers per nodeO(n)
You want…In Python
A sorted collection you add to and remove fromPython has no built-in BST. A popular choice is sortedcontainers.SortedList (pip install sortedcontainers): adds, removes and lookups in about O(log n).
Fast lookups in a list you keep sortedbisect.bisect_left finds a spot in O(log n); bisect.insort inserts, but shifting the list makes that O(n).
A tree that stays balanced by itselfThat is an AVL tree or a red-black tree. Java’s TreeMap and C++’s std::map are usually red-black trees.
Back a lessonHash mapUp nextHeaps