Sub topic 16
Rebuilding a tree from two traversals
This chapter assumes you can write recursive preorder and inorder traversals and know the Node class from earlier chapters. It also assumes you are comfortable with dictionaries and Big-O notation.
Why one traversal is not enough
A single traversal list does not identify a tree. Preorder [1, 2] fits a tree where 2 is the left child of 1, and it fits a tree where 2 is the right child. The list records the order of visits but not where each subtree begins and ends.
Inorder fixes this. Everything left of the root in the inorder list belongs to the left subtree, and everything right of it belongs to the right subtree.
The idea
Preorder visits the root first, so its first value is the root. Find that value in the inorder list and split the list there. The split gives the size of the left subtree. Preorder then holds the root, then the left subtree, then the right subtree, so you can recurse on both halves.
Implementation
The code below keeps a single position in the preorder list and passes only inorder bounds. A dictionary maps each value to its inorder index, so finding the root takes O(1) time. It assumes all values are unique.
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def build_tree(preorder, inorder):
index_of = {value: i for i, value in enumerate(inorder)}
pos = 0
def build(lo, hi):
nonlocal pos
if lo > hi:
return None
value = preorder[pos]
pos += 1
mid = index_of[value]
left = build(lo, mid - 1) # must run before the right call
right = build(mid + 1, hi)
return Node(value, left, right)
return build(0, len(inorder) - 1)
def postorder(node):
if node is None:
return []
return postorder(node.left) + postorder(node.right) + [node.value]
tree = build_tree([1, 2, 4, 5, 3], [4, 2, 5, 1, 3])
print(postorder(tree)) # [4, 5, 2, 3, 1]The result matches the five-node tree used throughout this tutorial.
Common errors
- Building the right subtree first. Preorder lists the left subtree before the right one, so
posonly works if the left call runs first. - Duplicate values. The dictionary keeps only one index per value, so the split can be wrong. Reconstruction needs unique values.
- Slicing lists on every call. This is correct but costs O(n) per call, which can make the whole build O(n²). Index bounds with a dictionary give O(n) time overall.
- Deep recursion. A degenerate tree makes the recursion n levels deep, so Python's default recursion limit can be hit on large inputs.
Other pairs
Postorder plus inorder also works. The root is the last postorder value, so you read postorder from the back and build the right subtree before the left.
Preorder plus postorder does not work in general. For preorder [1, 2] and postorder [2, 1], node 2 can be either child of 1. The tree is unique only if every node has zero or two children.
Exercise
Postorder is [4, 5, 2, 3, 1] and inorder is [4, 2, 5, 1, 3]. What is the root, and which values form its left subtree?
Show answer
The root is 1, the last postorder value. In inorder, the values left of 1 are 4, 2, 5, so they form the left subtree. The value 3 is the right subtree.
Exercise
Why can preorder and postorder alone fail to identify a tree?
Show answer
Neither list marks where the left subtree ends. A node with a single child looks the same in both lists whether that child is on the left or the right.