Trees & BST · Pattern 10 of 12

Build a tree from traversals, and serialize it

Preorder tells you the root first; inorder tells you which values are left of it. Serializing is the same idea in reverse: write a traversal with markers for null, then read it back in the same order.

3 variations · 5 problems · 4 with animated walkthroughs

Watch the lesson

Concepts first, then the problem and every approach, step by step.

Space to play or pause · ← → to jump a step · click or drag the bar to seek

When to use it

  • Rebuild a tree from two traversal arrays
  • Rebuild a BST from one traversal
  • Turn a tree into a string and back

The template

Tree Serialization / Deserialization
// preorder gives the root, inorder splits the rest into left and right
int pre;
Map<Integer, Integer> pos = new HashMap<>();                  // value -> index in inorder
TreeNode buildTree(int[] preorder, int[] inorder) {
    pre = 0;
    for (int i = 0; i < inorder.length; i++) pos.put(inorder[i], i);
    return build(preorder, 0, inorder.length - 1);
}
TreeNode build(int[] preorder, int lo, int hi) {               // inorder[lo..hi] is this subtree
    if (lo > hi) return null;
    TreeNode root = new TreeNode(preorder[pre++]);
    int mid = pos.get(root.val);
    root.left = build(preorder, lo, mid - 1);                  // left first, like preorder
    root.right = build(preorder, mid + 1, hi);
    return root;
}

// serialize as preorder with "#" for null; deserialize reads it back in the same order
String serialize(TreeNode root) {
    StringBuilder sb = new StringBuilder();
    write(root, sb);
    return sb.substring(1);                                    // drop the first comma
}
void write(TreeNode node, StringBuilder sb) {
    if (node == null) { sb.append(",#"); return; }
    sb.append(',').append(node.val);
    write(node.left, sb);
    write(node.right, sb);
}
TreeNode deserialize(String data) {
    return read(new ArrayDeque<>(Arrays.asList(data.split(","))));
}
TreeNode read(Deque<String> tokens) {
    String t = tokens.poll();
    if (t.equals("#")) return null;
    TreeNode node = new TreeNode(Integer.parseInt(t));
    node.left = read(tokens);
    node.right = read(tokens);
    return node;
}

The variations

  1. 1Rebuild from two traversals

    Take the next root from preorder (or the last from postorder), find it in inorder with a map, and recurse on the two sides. The traversal order decides which side you build first.

  2. 2A BST from one traversal

    The BST order replaces inorder. Pass an upper bound down: take the next preorder value while it is below the bound, the left child gets the node's value as its bound. O(n).

  3. 3Serialize with null markers

    Write preorder with # for every missing child, then read it back with one shared index. For an N-ary tree, write each node's child count after its value instead.

Mistakes to avoid

  • Searching inorder for the root on every call: O(n²). Build a value-to-index map once.
  • Inorder + postorder: postorder gives roots from the end, so build the right subtree before the left one.
  • Serializing without null markers: preorder alone cannot tell where a subtree ends (it can only for a BST, thanks to the order).

Mark it done once you can write the template from memory and you have solved the worked examples yourself.