Construct Binary Tree from Inorder and Postorder Traversal

Rebuild a binary tree from the two lists of values that its inorder and postorder walks produce.

A binary tree whose values are all different was walked in two orders, inorder and postorder, and each walk wrote its values into an array. Given the two arrays, inorder and postorder, rebuild the tree and return its root. The output lists the tree level by level, left to right, with null where a child is missing.

Example 1
Input: inorder = [9, 3, 15, 20, 7], postorder = [9, 15, 7, 20, 3]
Output: [3, 9, 20, null, null, 15, 7]
Example 2
Input: inorder = [-1], postorder = [-1]
Output: [-1]
Solution

The Idea

A binary tree is made of nodes. Each node holds a value and has at most two children, a left one and a right one. The node at the top is the root, and a node together with everything below it is called a subtree. To write a tree down as a flat list, you visit its nodes in a fixed order, and such a walk is called a traversal.

This problem uses two traversals. Inorder writes a node's left subtree, then the node, then its right subtree. Postorder writes the left subtree, then the right subtree, and the node itself last, after everything below it. For the tree in Example 1, inorder gives 9, 3, 15, 20, 7 and postorder gives 9, 15, 7, 20, 3.

Either array on its own could come from many different trees. So what does each one tell us, and how do the two fit together? Look at the picture below.

Postorder 9, 15, 7, 20, 3 ends with the root, 3. In inorder 9, 3, 15, 20, 7, the 3 splits the values: 9 on its left is the left subtree, and 15, 20, 7 on its right are the right subtree. In postorder the same values sit as left 9, then right 15, 7, 20, then the root.

In the row labelled postorder, the last value, 3, is the root of the whole tree, because postorder writes each node after everything below it. That names the root, but not which values hang to its left. The row labelled inorder answers that: inorder writes the left subtree before the root and the right subtree after it. So 9, left of 3, is the left subtree, and 15, 20, 7, right of 3, form the right subtree.

Now look at the braces under the postorder row. The left subtree's one value, 9, comes first, then the right subtree's values 15, 7, 20, then the root. And 15, 7, 20 is itself the postorder of the right subtree, so its last value, 20, is that subtree's root. Finding 20 in inorder splits 15 from 7 in the same way.

So the last postorder value is a root, and its place in inorder splits the other values into a left subtree and a right subtree. Each subtree is a smaller copy of the same problem, solved the same way. A method that solves a problem by calling itself on smaller parts is called recursive.

Solution Approach

Turning that idea into code means settling three things: how a call knows which values belong to its subtree, how to find a root's place in inorder without scanning, and which subtree to build first.

Describing a subtree

What does each recursive call need to know? A subtree's values sit side by side in inorder, so two positions, lo and hi, mark the first and last of them. For the right subtree of 3, counting positions from 0, that is positions 2 to 4, the values 15, 20, 7. When lo is greater than hi, the range is empty, so there is no child on that side and the call returns null. Copying parts of the arrays for each call would also work, but every copy costs time, while two positions cost nothing.

Finding a root in inorder

How do we find where 3 sits in inorder? Scanning inorder from the start works, but in a tree shaped like a chain each call can scan most of the array, about n²/2 steps in all for n values. Because the values are all different, a HashMap from each value to its position, filled once at the start, answers in one step.

Building the right subtree first

Which value is the next root? Postorder reads left subtree, right subtree, root. Read from the end, that becomes root, right subtree, left subtree. So a single position, next, starts at the last value of postorder and moves one step left for every node made. After 3, next points at 20, the root of the right subtree, not at 9. So each call builds its right subtree before its left one. By the time the right subtree is done, next has moved past 20, 7 and 15 and points at 9.

Java Solution

The method buildTree and its recursive helper build work in these steps:

  1. First, buildTree fills inorderIndex, a HashMap from each value in inorder to its position.
  2. It sets next to postorder.length - 1, the last position, and calls build with lo = 0 and hi = inorder.length - 1, the whole of inorder.
  3. In build, an empty range, lo > hi, returns null.
  4. Otherwise, build makes a new node, root, from postorder[next], and moves next one step left. It looks up the root's position in inorder and keeps it in mid.
  5. It builds root.right from the range mid + 1 to hi, then root.left from lo to mid - 1, and returns root.

A small TreeNode class holds one node, and the helper levelOrder prints a tree level by level, like the examples. The main method runs both examples, a tree where every node is a left child, one where every node is a right child, and a full tree of seven values.

Java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ConstructBinaryTreeFromInorderPostorder {

    static class TreeNode {
        int val;
        TreeNode left, right;
        TreeNode(int val) { this.val = val; }
    }

    private int next;                            // position of the next root in postorder
    private Map<Integer, Integer> inorderIndex;  // value -> its position in inorder

    public TreeNode buildTree(int[] inorder, int[] postorder) {
        inorderIndex = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            inorderIndex.put(inorder[i], i);
        }
        next = postorder.length - 1;
        return build(postorder, 0, inorder.length - 1);
    }

    private TreeNode build(int[] postorder, int lo, int hi) {
        if (lo > hi) {
            return null;                                 // empty range: no child here
        }
        TreeNode root = new TreeNode(postorder[next--]); // postorder lists the root last
        int mid = inorderIndex.get(root.val);
        root.right = build(postorder, mid + 1, hi);      // from the end: right part comes first
        root.left = build(postorder, lo, mid - 1);
        return root;
    }

    // Prints the tree level by level, with null for a missing child, like the examples.
    static String levelOrder(TreeNode root) {
        List<String> out = new ArrayList<>();
        List<TreeNode> order = new ArrayList<>();
        order.add(root);
        for (int i = 0; i < order.size(); i++) {
            TreeNode node = order.get(i);
            out.add(node == null ? "null" : String.valueOf(node.val));
            if (node != null) {
                order.add(node.left);
                order.add(node.right);
            }
        }
        while (!out.isEmpty() && out.get(out.size() - 1).equals("null")) {
            out.remove(out.size() - 1);
        }
        return out.toString();
    }

    static void run(int[] inorder, int[] postorder) {
        var builder = new ConstructBinaryTreeFromInorderPostorder();
        System.out.println(levelOrder(builder.buildTree(inorder, postorder)));
    }

    public static void main(String[] args) {
        run(new int[] {9, 3, 15, 20, 7}, new int[] {9, 15, 7, 20, 3});
        run(new int[] {-1}, new int[] {-1});
        run(new int[] {1, 2, 3}, new int[] {1, 2, 3});   // every node is a left child
        run(new int[] {1, 2, 3}, new int[] {3, 2, 1});   // every node is a right child
        run(new int[] {4, 2, 5, 1, 6, 3, 7}, new int[] {4, 5, 2, 6, 7, 3, 1});
    }
}

Running it prints:

Output
[3, 9, 20, null, null, 15, 7]
[-1]
[3, 2, null, 1]
[1, null, 2, null, 3]
[1, 2, 3, 4, 5, 6, 7]

Look at the first line, [3, 9, 20, null, null, 15, 7], the tree in the picture. The two null values are the missing children of 9, and 15 and 7 are the children of 20.

The third line comes from inorder [1, 2, 3] and postorder [1, 2, 3]. Postorder ends with 3, and in inorder every other value sits left of 3, so 3 has only a left child, 2, and 2 has only a left child, 1. The fourth line is the mirror image: postorder ends with 1, everything else sits right of 1 in inorder, and the tree leans right. The last line rebuilds a tree whose three levels are all full.

The order of the two recursive calls matters. With root.left built first, the call for the range left of 3, which holds only 9, takes 20 as its root, because next points at 20. Values land in the wrong places, and on Example 1 next runs past the start of postorder: the call throws ArrayIndexOutOfBoundsException with index -1.

Complexity

The work is one pass to fill the map, plus one call of build for each node and one for each missing child.

  • Time: O(n), for n values. Filling inorderIndex reads each value of inorder once. Then build makes one node per value, with one map lookup each, and the n + 1 calls that find an empty range return at once.
  • Space: O(n). The map holds all n values with their positions. The recursion goes as deep as the tree is tall, which is n for a chain like the third line of the output. The new tree itself is the output.

When preorder is given instead of postorder, the root comes first and the left subtree is built first: see Construct Binary Tree from Preorder and Inorder Traversal.