Data Structures19 sections · 729 units
Open in Course

Building Trees from Traversals

Reconstruction problems

Given traversal sequences, can you reconstruct the original tree?

Notice: inorder alone isn't enough (many trees share the same inorder). But inorder + preorder (or inorder + postorder) uniquely determines the tree.

Why? Preorder's first element is always the root. Find that root in inorder. Everything left of it is the left subtree, everything right is the right subtree. Recurse.

preorder: [3, 9, 20, 15, 7]
inorder:  [9, 3, 15, 20, 7]

Root = 3 (first in preorder)
In inorder: [9] | 3 | [15, 20, 7]
Left subtree has 1 node, right has 3
Recurse on each half

This reconstruction technique appears in many interview problems.