Construction from traversals
Preorder (or postorder) tells you which value is the root; inorder tells you which values are on its left and right. Together they rebuild a tree with distinct values exactly. Preorder and postorder alone are not enough. A bracket string like 4(2(3)(1))(6(5)) is parsed by reading a number and then up to two bracketed subtrees.
How to recognise it
- Two traversals are given and the tree must be rebuilt.
- A string encodes a tree with brackets.
- The question asks whether two traversals determine a tree.
Root first, then split
where = map from value to its index in inorder
build(lo, hi): # the part of inorder for this subtree
if lo > hi: return null
root = next value of preorder
mid = where[root]
root.left = build(lo, mid - 1)
root.right = build(mid + 1, hi)
What a node, a child, a leaf and a level are is on the Structures page.
| Pair | Unique? |
|---|---|
| preorder + inorder | yes |
| postorder + inorder | yes (read postorder backwards, build right first) |
| preorder + postorder | no, in general |
| any one alone | no |
These assume distinct values.
Bracket strings
4(2(3)(1))(6(5)): read the number 4, then a bracketed left subtree, then a bracketed right subtree. An empty
() marks a missing left child when a right child follows.
Common mistakes
- Searching inorder for the root each time (O(n²)) instead of using a map.
- Building the left subtree first when reading postorder backwards.
Problems
- Requirements needed to construct a unique BTmediumguide ready
- Construct Binary Tree from Preorder and Inorder Traversalmediumguide ready
- Construct Binary Tree from Inorder and Postorder Traversalmediumguide ready
- Construct Binary Tree from String with Bracket Representationmediumguide ready