AlgoTales · Roadmap

Construct tree from traversals

Advanced · 12 min · code in PHP, JavaScript, Java and Go

Where you will meet this in real life

Given two lists produced by walking a tree in different orders, you can rebuild the original tree exactly. One list tells you who the boss of each part is, the other tells you who sits on which side of the boss.

Practical use cases

  • Web app: Restoring a saved page-builder layout. A page-builder tool stored a layout as two compact lists to save space. When the user reopens the page, the app uses the first list to find each block's parent and the second to split left from right. The full nested layout returns without storing any extra links.
  • Web app: Importing an org chart from two exports. An HR system exports a company hierarchy as two lists of names, one for each reading order. The import script combines them to rebuild who reports to whom. Staff stop typing the chart by hand, and 1,000 people are loaded in seconds.
  • System: Compression and expression parsing. Some compression formats, and compilers working with expression trees, store a tree as two traversals and rebuild it when needed. It is a space-saving way to store structure. The catch is that every value must be unique, otherwise the tree cannot be rebuilt without guessing.

The story: The Detective and the Two Lists

Inspector Aarav was handed a puzzle: a family tree was lost in a fire, but two sheets survived. Sheet one listed names in the order the family walked into a wedding hall: parent first, then everyone from the left branch, then everyone from the right branch (preorder). Sheet two listed them in the order they sat on a long bench, left to right (inorder).

Aarav noticed something clever. On sheet one, the first name is always the top ancestor, because parents walk in first. Then he found that name on sheet two. Everyone sitting to its left belonged to the left branch, and everyone to its right belonged to the right branch!

He now had two smaller puzzles of exactly the same kind. The next unused name on sheet one is the top of the left branch; he finds it in the left part of the bench list and splits again. He kept going until each part was empty, and the whole tree stood on the table. Using two traversals to rebuild a tree is the classic construct tree from traversals.

How to spot this problem, and where you need it

You have two different reading orders of the same tree, perhaps from a log, export or test case, and you need to recover the actual tree shape.

Signs you need it

  • The problem gives "preorder and inorder" or "postorder and inorder" arrays and asks for the tree.
  • You hold a flat export of a hierarchy but lost the parent links and need to recover who is under whom.
  • All values are unique, since duplicates would make the rebuilding ambiguous.

Where to use it in a project

  • Restoring compact saved layouts or hierarchies from two stored lists.
  • Test tools that rebuild an expected tree from traversal output to compare it with what the code produced.

The solution

Take the first value of the preorder list as the root. Find it in the inorder list: everything to its left belongs to the left subtree, everything to its right to the right subtree. Use those sizes to cut the preorder list into the matching two parts and repeat the same step on each. A map from value to position avoids searching again and again.

Payoff: Before: scanning the inorder list again for every node, slow on 10,000 nodes. After: a lookup map makes each step instant, so the rebuild is a single pass.

Explain it like I am 8

One list tells you who the boss is (the first name). The other list is a row of people sitting in order, and the boss sits right in the middle: everyone to the left is on the left team, everyone to the right is on the right team. Do the same again inside each team.

How it works, step by step

  1. In preorder, the first unused value is the root of the current part.
  2. Find that value in the inorder list. Everything left of it forms the left subtree, everything right of it the right subtree.
  3. Build the left subtree first (using the next preorder values), then the right subtree.
  4. Stop when a part is empty. Tip: store each value's inorder position in a map so finding it is instant.

The code in four languages

PHP

<?php
class Node {
    public ?Node $left = null;
    public ?Node $right = null;
    public function __construct(public int $val) {}
}

function buildTree(array $pre, array $in): ?Node {
    $pos = array_flip($in);                       // value => position in inorder (instant lookup)
    $p = 0;                                       // next unused preorder index
    $build = function (int $lo, int $hi) use (&$build, &$p, $pre, $pos): ?Node {
        if ($lo > $hi) return null;               // empty part
        $val = $pre[$p++];                        // next preorder value is the root
        $node = new Node($val);
        $mid = $pos[$val];                        // where it sits in inorder
        $node->left = $build($lo, $mid - 1);      // left part first
        $node->right = $build($mid + 1, $hi);
        return $node;
    };
    return $build(0, count($in) - 1);
}

function postorder(?Node $n, array &$out): void {
    if ($n === null) return;
    postorder($n->left, $out);
    postorder($n->right, $out);
    $out[] = $n->val;
}

$pre = [8, 3, 1, 6, 4, 7, 10, 14, 13];
$in  = [1, 3, 4, 6, 7, 8, 10, 13, 14];
$root = buildTree($pre, $in);
$out = [];
postorder($root, $out);                           // a third view proves the tree is right
echo implode(' ', $out), PHP_EOL;                 // 1 4 7 6 3 13 14 10 8

JavaScript

class Node {
  constructor(val) { this.val = val; this.left = null; this.right = null; }
}

function buildTree(pre, inorder) {
  const pos = new Map();                          // value -> position in inorder (instant lookup)
  inorder.forEach((v, i) => pos.set(v, i));
  let p = 0;                                      // next unused preorder index
  function build(lo, hi) {
    if (lo > hi) return null;                     // empty part
    const val = pre[p++];                         // next preorder value is the root
    const node = new Node(val);
    const mid = pos.get(val);                     // where it sits in inorder
    node.left = build(lo, mid - 1);               // left part first
    node.right = build(mid + 1, hi);
    return node;
  }
  return build(0, inorder.length - 1);
}

function postorder(n, out) {
  if (n === null) return;
  postorder(n.left, out);
  postorder(n.right, out);
  out.push(n.val);
}

const pre = [8, 3, 1, 6, 4, 7, 10, 14, 13];
const inorder = [1, 3, 4, 6, 7, 8, 10, 13, 14];
const root = buildTree(pre, inorder);
const out = [];
postorder(root, out);                             // a third view proves the tree is right
console.log(out.join(' '));                       // 1 4 7 6 3 13 14 10 8

Java

import java.util.*;
import java.util.stream.*;

public class Main {
    static class Node {
        int val;
        Node left, right;
        Node(int val) { this.val = val; }
    }

    static int p;                                       // next unused preorder index

    static Node buildTree(int[] pre, int[] in) {
        Map<Integer, Integer> pos = new HashMap<>();    // value -> position in inorder (instant lookup)
        for (int i = 0; i < in.length; i++) pos.put(in[i], i);
        p = 0;
        return build(pre, pos, 0, in.length - 1);
    }

    static Node build(int[] pre, Map<Integer, Integer> pos, int lo, int hi) {
        if (lo > hi) return null;                       // empty part
        int val = pre[p++];                             // next preorder value is the root
        Node node = new Node(val);
        int mid = pos.get(val);                         // where it sits in inorder
        node.left = build(pre, pos, lo, mid - 1);       // left part first
        node.right = build(pre, pos, mid + 1, hi);
        return node;
    }

    static void postorder(Node n, List<Integer> out) {
        if (n == null) return;
        postorder(n.left, out);
        postorder(n.right, out);
        out.add(n.val);
    }

    public static void main(String[] args) {
        int[] pre = {8, 3, 1, 6, 4, 7, 10, 14, 13};
        int[] in  = {1, 3, 4, 6, 7, 8, 10, 13, 14};
        Node root = buildTree(pre, in);
        List<Integer> out = new ArrayList<>();
        postorder(root, out);                           // a third view proves the tree is right
        System.out.println(out.stream().map(String::valueOf).collect(Collectors.joining(" ")));  // 1 4 7 6 3 13 14 10 8
    }
}

Go

package main

import (
	"fmt"
	"strings"
)

type Node struct {
	val         int
	left, right *Node
}

func buildTree(pre, in []int) *Node {
	pos := map[int]int{} // value -> position in inorder (instant lookup)
	for i, v := range in {
		pos[v] = i
	}
	p := 0 // next unused preorder index
	var build func(lo, hi int) *Node
	build = func(lo, hi int) *Node {
		if lo > hi {
			return nil // empty part
		}
		val := pre[p] // next preorder value is the root
		p++
		node := &Node{val: val}
		mid := pos[val]              // where it sits in inorder
		node.left = build(lo, mid-1) // left part first
		node.right = build(mid+1, hi)
		return node
	}
	return build(0, len(in)-1)
}

func postorder(n *Node, out *[]string) {
	if n == nil {
		return
	}
	postorder(n.left, out)
	postorder(n.right, out)
	*out = append(*out, fmt.Sprint(n.val))
}

func main() {
	pre := []int{8, 3, 1, 6, 4, 7, 10, 14, 13}
	in := []int{1, 3, 4, 6, 7, 8, 10, 13, 14}
	root := buildTree(pre, in)
	var out []string
	postorder(root, &out)               // a third view proves the tree is right
	fmt.Println(strings.Join(out, " ")) // 1 4 7 6 3 13 14 10 8
}

Time: O(n) · Extra space: O(n). With a map for inorder positions each node is built once; without the map, searching the list each time can cost O(n²).

Watch out for

  • Building the right subtree before the left. Preorder visits left before right, so the left must consume its preorder values first.
  • Mixing up the lists: the root comes from preorder (or the last of postorder), the split comes from inorder.
  • Trying to rebuild from preorder and postorder alone. Without inorder the tree is not unique unless every node has 0 or 2 children.

Quick check

  1. Where is the root of the whole tree?
    • Last item of preorder
    • First item of preorder
    • Middle of preorder
  2. What does the inorder list tell us once we know the root?
    • Which values are in the left and right subtree
    • The height of the tree
    • The leaves
  3. Which subtree do we build first from preorder?
    • Right
    • Either one
    • Left