Learn / Trees

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.

PairUnique?
preorder + inorderyes
postorder + inorderyes (read postorder backwards, build right first)
preorder + postorderno, in general
any one aloneno

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

0 of 4 solved

Check yourself

Preorder [3, 9, 20, 15, 7] and inorder [9, 3, 15, 20, 7]. What is the root's left subtree?

Which pair cannot always rebuild a unique tree?

When rebuilding from inorder and postorder, which subtree is built first?