Binary Trees
A binary tree is a tree where every node has at most two children, called the left child and the right child. The distinction matters: a node with only a left child is a different tree from a node with only a right child.
A
/ \
B C
/ \ \
D E FBinary trees are the basis of binary search trees, AVL trees, heaps, expression trees and Huffman codes.
A node class
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
root = Node("A",
Node("B", Node("D"), Node("E")),
Node("C", None, Node("F")))
print(root.value, root.left.value, root.right.value)
print(root.left.right.value) # A -> B -> E
print(root.right.left) # C has no left childA B C
E
None
Measuring a binary tree
The recursive pattern from the previous lesson becomes even simpler with exactly two child slots. An empty subtree (None) is the base case:
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
root = Node("A", Node("B", Node("D"), Node("E")), Node("C", None, Node("F")))
def size(node):
return 0 if node is None else 1 + size(node.left) + size(node.right)
def height(node): # an empty tree has height -1
return -1 if node is None else 1 + max(height(node.left), height(node.right))
def count_leaves(node):
if node is None:
return 0
if node.left is None and node.right is None:
return 1
return count_leaves(node.left) + count_leaves(node.right)
print("size:", size(root), "height:", height(root), "leaves:", count_leaves(root))size: 6 height: 2 leaves: 3
Shapes of binary trees
| Kind | Definition | Our example? |
|---|---|---|
| Full | every node has 0 or 2 children | no: C has one child |
| Complete | all levels are full except possibly the last, which is filled from the left | no: C has no left child |
| Perfect | all internal nodes have 2 children and all leaves are on the same level | no |
| Balanced | for every node, the heights of the left and right subtrees differ by at most 1 | yes |
| Degenerate | every node has at most one child (it's really a linked list) | no |
The shape decides the height, and the height decides the speed of most tree operations. A perfect tree of height h has 2^(h+1) - 1 nodes, so the height grows only logarithmically. A degenerate tree with n nodes has height n - 1.
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
def height(node):
return -1 if node is None else 1 + max(height(node.left), height(node.right))
def is_balanced(node):
if node is None:
return True
return (abs(height(node.left) - height(node.right)) <= 1
and is_balanced(node.left) and is_balanced(node.right))
def is_full(node):
if node is None:
return True
if (node.left is None) != (node.right is None):
return False
return is_full(node.left) and is_full(node.right)
example = Node("A", Node("B", Node("D"), Node("E")), Node("C", None, Node("F")))
chain = Node(1, None, Node(2, None, Node(3, None, Node(4))))
print("example: balanced", is_balanced(example), "full", is_full(example))
print("chain: balanced", is_balanced(chain), "height", height(chain))
for h in range(5):
print(f"perfect tree of height {h}: {2 ** (h + 1) - 1} nodes")example: balanced True full False
chain: balanced False height 3
perfect tree of height 0: 1 nodes
perfect tree of height 1: 3 nodes
perfect tree of height 2: 7 nodes
perfect tree of height 3: 15 nodes
perfect tree of height 4: 31 nodes
Drawing a tree sideways
A quick way to see a binary tree in text is to print it rotated 90°: the right subtree first (on top), then the node, then the left subtree, indented by depth.
class Node:
def __init__(self, value, left=None, right=None):
self.value, self.left, self.right = value, left, right
def draw(node, depth=0):
if node is None:
return
draw(node.right, depth + 1)
print(" " * depth + str(node.value))
draw(node.left, depth + 1)
draw(Node("A", Node("B", Node("D"), Node("E")), Node("C", None, Node("F")))) F
C
A
E
B
D
Tilt your head to the left: A is the root, C and F are on the right.
Visiting every node
To process every node of a binary tree, you must decide when to handle a node relative to its subtrees. That gives the three classic depth-first traversals, each with its own lesson next:
| Traversal | Order | Our example |
|---|---|---|
| Pre-order | node, left, right | A B D E C F |
| In-order | left, node, right | D B E A C F |
| Post-order | left, right, node | D E B F C A |
There is also level-order traversal (breadth-first): visit level by level using a queue, which gives A B C D E F here.
Test yourself
What is the maximum number of children a node in a binary tree can have?
- 1
- 2
- 3
- Unlimited
How many nodes does a perfect binary tree of height 3 have?
- 7
- 8
- 15
- 16
Which kind of tree has the worst (largest) height for n nodes?
- Perfect
- Complete
- Balanced
- Degenerate