6.2Binary Tree with an Array
Preorder traversal
To traverse a tree is to visit each of its nodes once. A list had only one path; in a tree two paths leave every node and you have to decide which one to take first. In a preorder traversal you visit the node itself first, then its left subtree, then its right subtree.
- The preorder order, root, left, right, and how to find a tree's preorder output by hand
- How recursion moves through a tree in an array by index, with
2*i+1and2*i+2 - Why the
i >= countbase case also covers missing children
1Idea
Every node is the root of its own subtree. That is why the traversal is very short with recursion: preorder(i) prints items[i] first, then does the same for the left child's index 2*i+1, then for the right child's index 2*i+2. The first call uses the root's index, 0.
The stopping rule is a single line: if i >= count there is no node at that index and the call returns at once. Since the tree is filled into the next free place, the used cells run from 0 to count - 1 with no gaps. The child indexes of a leaf always fall outside count, so at a leaf both calls return at once.
For the example tree the preorder output is 10 20 40 50 30 60. To find it by hand, follow this rule: print a node the first time you reach it, then go left; when the left side is done, move right.
The same traversal is written with linked nodes as preorder(root). The only difference is how you reach a child: 2*i+1 in the array, root->left with linked nodes. A missing child is i >= count in the array and NULL with linked nodes.
2Step by step
The drawing shows the tree on top and its array below. A visited node turns green, and the tree node gets its position in the output under it; the array indexes stay the same. The stack under the drawing shows the calls that have not finished.
- Start. The tree has 6 nodes,
countis 6. The used cells run from 0 to 5, and cell 6 is empty. preorder(0)starts at the root. 0 < 6, so there is a node. The root is printed first: 10. Output:10. Then we go down to the left child, index 1.preorder(1): 1 < 6, so there is a node. It is printed first: 20. Output:10 20. Then we go down to the left child, index 3.preorder(3): 3 < 6, so there is a node. It is printed first: 40. Output:10 20 40. 40 is a leaf: its child indexes 7 and 8 are outsidecount.preorder(7): 7 ≥ 6, there is no node at this index. This is the base case: the call returns without printing. Both child indexes of 40, 7 and 8, are outsidecount.preorder(4): 4 < 6, so there is a node. It is printed first: 50. Output:10 20 40 50. 50 is a leaf: its child indexes 9 and 10 are outsidecount.preorder(2): 2 < 6, so there is a node. It is printed first: 30. Output:10 20 40 50 30. Then we go down to the left child, index 5.preorder(5): 5 < 6, so there is a node. It is printed first: 60. Output:10 20 40 50 30 60. 60 is a leaf: its child indexes 11 and 12 are outsidecount. That was the last node.preorder(6): the right child of 30 would be at index2*2+2 = 6, but 6 ≥count. The cell is empty, so the call returns without printing.- Done. The preorder output is
10 20 40 50 30 60. Every node was printed once and the stack is empty.
#define CAPACITY 15 struct Tree { int items[CAPACITY]; int count;}; void preorder(struct Tree* t, int i) { if (i >= t->count) { return; // empty place: no node } printf("%d ", t->items[i]); // the root first preorder(t, 2 * i + 1); // then the left subtree preorder(t, 2 * i + 2); // the right subtree last}class ArrayTree { int[] items; int count = 0; ArrayTree(int capacity) { items = new int[capacity]; } void preorder(int i) { if (i >= count) { return; // empty place: no node } System.out.print(items[i] + " "); // the root first preorder(2 * i + 1); // then the left subtree preorder(2 * i + 2); // the right subtree last }}class ArrayTree: def __init__(self, capacity): self.items = [None] * capacity self.count = 0 def preorder(self, i=0): if i >= self.count: return # empty place: no node print(self.items[i], end=" ") # the root first self.preorder(2 * i + 1) # then the left subtree self.preorder(2 * i + 2) # the right subtree lastThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Each node is printed once. The calls for missing children are at most the number of nodes plus one, so the total work grows with n.
The call stack gets at most as deep as the tree's height: one frame per level from the root to the deepest leaf, plus one for a missing child. In an array the tree is always complete, so h is about log n.
Preorder with linked nodes also takes O(n). There the tree can be unbalanced and the stack can go n frames deep in the worst case; that cannot happen with the complete tree in an array.
4Common mistake
The most common mistake is forgetting the base case, or checking only the root:
void preorder(struct Tree* t, int i) { printf("%d ", t->items[i]); // i may be >= count! preorder(t, 2 * i + 1); preorder(t, 2 * i + 2);}This code never stops: the index grows on every call and reads past the end of the array. The check must come before printing, in every call. Another mistake is writing the child indexes as 2*i and 2*i+1; that formula is for arrays that start at 1, and in an array that starts at 0 it makes the root its own left child.
5Try it
Let the array [5, 3, 8, 1, 4] hold a binary tree in level order (count = 5). What is the preorder output?
The answer is B. The root is 5. Its left child is items[1] = 3, whose children are items[3] = 1 and items[4] = 4. The right child is items[2] = 8. Preorder: 5, then the left subtree 3 1 4, then 8.
Show the answer
The answer is B. The root is 5. Its left child is items[1] = 3, whose children are items[3] = 1 and items[4] = 4. The right child is items[2] = 8. Preorder: 5, then the left subtree 3 1 4, then 8.
In a tree with count = 6, how many empty calls (calls that return at once) does preorder(5) make?
The answer is C. items[5] is a leaf. Its child indexes are 2*5+1 = 11 and 2*5+2 = 12, both outside count. So two calls are made and both return at once in the base case.
Show the answer
The answer is C. items[5] is a leaf. Its child indexes are 2*5+1 = 11 and 2*5+2 = 12, both outside count. So two calls are made and both return at once in the base case.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.