Sub topic 6
Rebuilding a tree from two traversals
This chapter assumes you can write the four traversals (preorder, inorder, postorder, level order) and read a recursive function. It uses the Node class and the traversal functions from the previous chapter. Every key in the examples is distinct, and the chapter points out where that matters.
Why one traversal is not enough
A single traversal does not identify a binary tree. Take the preorder sequence A B C. All five of these shapes produce it:
- A has a left child B, and B has a left child C.
- A has a left child B, and B has a right child C.
- A has a left child B and a right child C.
- A has only a right child B, and B has a left child C.
- A has only a right child B, and B has a right child C.
For n nodes, the number of binary tree shapes sharing one preorder sequence is the Catalan number C(n). Here C(3) = 5. The same holds for inorder and postorder. One sequence lists the keys but loses the structure, because it does not say where one subtree ends and the next begins.
Two traversals can recover that information, but only for certain pairs.
Which pairs determine the tree
| Pair given | Determines the tree? | Why |
|---|---|---|
| Preorder + inorder | Yes | Preorder gives the root, inorder splits the rest |
| Postorder + inorder | Yes | Postorder gives the root (last element), inorder splits the rest |
| Level order + inorder | Yes | The first level-order key is the root, inorder splits the rest |
| Preorder + postorder | Only if every node has 0 or 2 children | Without that, a lone child could be left or right |
Inorder is the key ingredient in the first three pairs. It is the only traversal that separates the left subtree's keys from the right subtree's keys around the root. Preorder, postorder, and level order each tell you which key is the root of a given group, but not which keys fall to its left or right.
Preorder + inorder
The preorder sequence is root, left subtree, right subtree. The inorder sequence is left subtree, root, right subtree. This gives a recursive rule:
- The first key of the preorder sequence is the root.
- Find that key in the inorder sequence. Everything to its left is the left subtree. Everything to its right is the right subtree.
- If the left part has k keys, the next k keys of preorder are the left subtree's preorder. The rest are the right subtree's preorder.
- Repeat on each side.
Worked example
Preorder: A B D E C F. Inorder: D B E A F C.
- The root is A. In the inorder sequence,
D B Eis left of A andF Cis right of A. - The left part has 3 keys, so the left preorder is
B D Eand the right preorder isC F. - Left subtree: the root is B. In
D B E, D is left of B and E is right of B. So D is the left child and E is the right child. - Right subtree: the root is C. In
F C, F is left of C and nothing is right of C. So F is the left child and C has no right child.
A quick check: the postorder of this tree is D E B F C A. Reading the tree off the diagram and traversing it is how you verify your answer in an exam.
Code
The build function below is the direct version of the rule. The program also prints the postorder of the rebuilt tree.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def build(preorder_seq, inorder_seq):
if not preorder_seq:
return None
root = Node(preorder_seq[0])
k = inorder_seq.index(preorder_seq[0])
root.left = build(preorder_seq[1:k + 1], inorder_seq[:k])
root.right = build(preorder_seq[k + 1:], inorder_seq[k + 1:])
return root
def postorder(node, out):
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.key)
tree = build(list("ABDECF"), list("DBEAFC"))
result = []
postorder(tree, result)
print(" ".join(result))Running it prints D E B F C A.
The variable k is the size of the left subtree. It is the number of keys before the root in the inorder sequence. Both the preorder slice [1:k + 1] and the inorder slice [:k] must have exactly k keys. If the two inputs are not traversals of the same tree, the slices mismatch and the result is wrong or the call raises an error.
Cost
inorder_seq.index scans the sequence, and the slices copy it. In the worst case (a skewed tree) each call does O(n) work and there are n calls, so the total is O(n²). You can reach O(n) with two changes:
- Build a dictionary from key to inorder position once.
- Pass index bounds instead of slices, and consume the preorder sequence one key at a time.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def build_fast(preorder_seq, inorder_seq):
pos = {key: i for i, key in enumerate(inorder_seq)}
keys = iter(preorder_seq)
def helper(lo, hi):
if lo > hi:
return None
key = next(keys)
root = Node(key)
k = pos[key]
root.left = helper(lo, k - 1)
root.right = helper(k + 1, hi)
return root
return helper(0, len(inorder_seq) - 1)
root = build_fast(list("ABDECF"), list("DBEAFC"))
print(root.key, root.left.key, root.right.key)This prints A B C. The order of the two recursive calls matters. Preorder lists the left subtree before the right one, so the left call must consume its keys first.
Postorder + inorder
Postorder is left subtree, right subtree, root, so the root is the last key. The rest of the rule is the same, with one trap: in the postorder sequence the left block comes first, then the right block, then the root.
Worked example. Inorder: D B E A F C. Postorder: D E B F C A.
- The root is A (the last postorder key). Inorder gives left =
D B Eand right =F C. - The left part has 3 keys, so the left postorder is
D E Band the right postorder isF C. - In
D E Bthe root is B. In inorder, D is left of B and E is right of B. - In
F Cthe root is C. In inorder, F is left of C.
This is the same tree as before. In code, a common trick is to read the postorder sequence from the end and build the right subtree first, because reading backwards gives root, right, left.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def build_post(postorder_seq, inorder_seq):
pos = {key: i for i, key in enumerate(inorder_seq)}
keys = reversed(postorder_seq)
def helper(lo, hi):
if lo > hi:
return None
key = next(keys)
root = Node(key)
k = pos[key]
root.right = helper(k + 1, hi)
root.left = helper(lo, k - 1)
return root
return helper(0, len(inorder_seq) - 1)
root = build_post(list("DEBFCA"), list("DBEAFC"))
print(root.key, root.left.key, root.right.key)This prints A B C.
Why preorder + postorder is ambiguous
Consider the tree with root A and one child B. Its preorder is A B and its postorder is B A. The tree is the same sequence pair whether B is the left child or the right child. Preorder and postorder both put a subtree's keys in one block, but neither one says which side of the root that block is on.
If every internal node has exactly two children (a full binary tree), the pair does work:
- The first preorder key is the root. The second preorder key is the root of the left subtree.
- Find that second key in the postorder sequence. Its position tells you how large the left subtree is, because a subtree's root is the last key of its postorder block.
- Split both sequences and recurse.
Example. Preorder: A B D E C. Postorder: D E B C A. The root is A and the left subtree's root is B. B is at index 2 in postorder, so the left subtree has 3 keys (D E B). The left preorder is B D E and the right is C. The tree is A with left child B (children D and E) and right child C.
Level order + inorder
The first level-order key is the root. Inorder splits the remaining keys into a left set and a right set. The left subtree's level order is the level-order sequence with the keys from the right set removed (keeping the order), and the same for the right subtree. The idea is the same as before, but the bookkeeping is a filter instead of a slice, so exam questions use it less often.
Duplicate keys
All three constructions depend on finding the root's position in the inorder sequence. With duplicate keys, index may return the wrong occurrence, and two different trees can give identical sequences. Reconstruction questions therefore state that keys are distinct. Treat that as a required condition.
Binary search trees need only one traversal
A BST is a special case. Its inorder traversal is the keys in sorted order. If you are told the tree is a BST, you can get the inorder sequence yourself by sorting the keys of any one traversal. A single preorder, postorder, or level-order sequence then identifies a BST uniquely, because you now have a valid pair.
Example. A BST has preorder 50 30 20 40 70 60 80. Sorting gives inorder 20 30 40 50 60 70 80. The root is 50, the left block is 20 30 40 with root 30, and the right block is 60 70 80 with root 70. The postorder is 20 40 30 60 80 70 50.
Common errors
- Taking the wrong block as the left subtree in postorder. The left block comes first in postorder, and the root comes last.
- Using the size of the left subtree from the wrong sequence. Count it from the inorder sequence, then apply that count to the other sequence.
- Assuming preorder + postorder determines the tree.
- Forgetting that a node with one child still needs a side. Inorder is what tells you which side.
Exercise
A binary tree has inorder 4 2 5 1 3 6 and postorder 4 5 2 6 3 1. Draw the tree and give its preorder.
Show answer
The root is 1 (last postorder key). Inorder gives left 4 2 5 and right 3 6. The left postorder is 4 5 2, so its root is 2 with left child 4 and right child 5. The right postorder is 6 3, so its root is 3. In inorder 3 6, 6 is after 3, so 6 is the right child of 3. The preorder is 1 2 4 5 3 6.
Exercise
A BST has preorder 50 30 20 40 70 60 80. Give its postorder without drawing the whole tree, and state why a single traversal was enough.
Show answer
Sorting the keys gives the inorder sequence 20 30 40 50 60 70 80, so preorder + inorder determines the tree. The tree has root 50, left subtree 30 (children 20 and 40), and right subtree 70 (children 60 and 80). The postorder is 20 40 30 60 80 70 50. A single traversal was enough because the BST property makes inorder equal to the sorted keys.
Exercise
Preorder is A B and postorder is B A. How many binary trees match, and why?
Show answer
Two trees match. A is the root and B is its only child. B can be the left child or the right child, and both choices give preorder A B and postorder B A. The pair cannot distinguish them because the tree is not full.