Sub topic 2
Binary Trees and Their Special Forms
Assume you know basic recursion, object references, arrays, linked lists, and Big-O notation. This chapter uses height measured in edges. Thus, a one-node tree has height 0, and an empty tree has height -1.
What makes a tree binary?
A binary tree is a tree in which each node has at most two children. We usually name the children left and right. A node may have zero, one, or two children.
The number of children of a node is its degree. In a binary tree, every node has degree 0, 1, or 2. The order matters: a left child and a right child are different positions, even if they contain equal-looking data.
Consider this tree:
Ais the root.D,E, andFare leaves because they have no children.Bhas degree 2.Chas degree 1.- The tree is binary because no node has more than two children.
Four important forms
These names describe the shape of a binary tree.
| Form | Definition | Main feature |
|---|---|---|
| Full | Every node has either 0 or 2 children | No node has exactly one child |
| Complete | Every level is full except possibly the last, which is filled left to right | Array storage is efficient |
| Perfect | Every internal node has 2 children, and all leaves are at the same depth | Every level is completely full |
| Skewed | Each node has at most one child | Shape resembles a linked list |
A full binary tree forbids nodes with exactly one child. It can have leaves at different depths.
A complete binary tree fills each level from left to right. Missing nodes can occur only on the last level. A gap on the last level followed by another node violates completeness.
A perfect binary tree is both full and complete. If its height is h, it has exactly 2^(h + 1) - 1 nodes and 2^h leaves.
A skewed tree is an extreme shape. If every node has only a left child, or every node has only a right child, its height is n - 1 for n nodes. Operations that follow a root-to-leaf path can then take linear time.
Useful relationships
For a full binary tree with I internal nodes and L leaves:
L = I + 1
Therefore, the total number of nodes is:
N = I + L = 2I + 1 = 2L - 1
A binary tree with height h has at most 2^(h + 1) - 1 nodes. This maximum occurs for a perfect tree.
For a nonempty binary tree with n nodes, the smallest possible height is:
ceil(log2(n + 1)) - 1
This occurs when the nodes are arranged as evenly as possible. The largest possible height is n - 1, which occurs in a skewed tree.
Exercise
A full binary tree has 11 internal nodes. How many leaves and total nodes does it have?
Show answer
It has 12 leaves because L = I + 1. Its total is 23 nodes because N = 2I + 1.