CAP7004 · Unit 5: Trees
Binary trees and traversals
8 practice questions
Key points
- Preorder root-L-R, inorder L-root-R, postorder L-R-root
- Level order uses a queue
- Max nodes at height h is 2^(h+1) - 1
- Inorder + preorder/postorder reconstructs the tree
A binary tree has nodes with at most two children (left and right). Terms: root (top), leaf (no children), height (edges on the longest root-to-leaf path; a single node has height 0), depth of a node (edges from the root), level (depth + 1 in many texts).
Counting facts: level L (root at 0) has at most 2^L nodes; a tree of height h has at most 2^(h+1) - 1 nodes (15 for h = 3). In a full binary tree (every node has 0 or 2 children), leaves = internal nodes + 1.
Traversals of the tree with root 1, children 2 and 3, node 2 having children 4 and 5, node 3 having right child 6:
- Preorder (root, left, right): 1 2 4 5 3 6
- Inorder (left, root, right): 4 2 5 1 3 6
- Postorder (left, right, root): 4 5 2 6 3 1
- Level order (breadth first, uses a queue): 1 2 3 4 5 6
def inorder(n):
return inorder(n.left) + [n.v] + inorder(n.right) if n else []
Each traversal visits n nodes: O(n) time; recursion uses O(h) stack.
Reconstruction: inorder plus either preorder or postorder identifies a unique tree. Preorder alone does not. The first preorder item (or last postorder item) is the root; find it in inorder to split left and right.
Exam pitfall: do not confuse height measured in edges with height measured in nodes; state which convention is used.
Try two questions
A node with no children is called a:
- Root
- Parent
- Leaf
- Sibling
Show the answer
C. Leaves have no left or right child.
The maximum number of nodes in a binary tree of height 3 (height counted in edges) is:
- 16
- 8
- 7
- 15
Show the answer
D. 1 + 2 + 4 + 8 = 15 = 2^4 - 1.