Construct Binary Tree from Preorder and Inorder Traversal

Pattern: Construction from traversals

medium

Preorder tells you each root first; its position in the inorder splits the values into the left and right subtrees. A map from value to inorder index makes each split O(1), and recursing on index ranges builds the tree in O(n).

The problem

Rebuild the binary tree from its preorder and inorder traversals (values are distinct) and return its root. preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7] gives [3, 9, 20, null, null, 15, 7]. Trees in the examples are written in level order, with null for a missing child, as on LeetCode.

Think first

  • Which value is the root?
  • What does the root's position in inorder tell you?
  • Which preorder value is the next root to place?

Hints

    Brute force, and why it fails

    Search the inorder for each root and slice arrays: O(n²) time and memory.

    The key insight

    Consuming preorder left to right in step with the recursion means each root is just 'the next value', and the map finds its split instantly.

    Dry run

    root3

    preorder [3, 9, 20, 15, 7], inorder [9, 3, 15, 20, 7]. The root is 3; in inorder, [9] is left and [15, 20, 7] is right.

    Step 1 of 3

    The plan

    where = value -> inorder index
    build(lo, hi): if lo > hi: null
                   root = next preorder value; m = where[root]
                   root.left = build(lo, m - 1); root.right = build(m + 1, hi)
    

    Complexity

    Time
    O(n)
    Space
    O(n)

    Each value is placed once; the map holds n entries.

    Edge cases

    • One value.
    • A chain to the left: inorder is reversed preorder.
    • Empty arrays: an empty tree.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        private int next;                           // the next preorder value to place
        private Map<Integer, Integer> where;        // value -> its index in inorder
    
        public TreeNode buildTree(int[] preorder, int[] inorder) {
            next = 0;
            where = new HashMap<>();
            for (int i = 0; i < inorder.length; i++) where.put(inorder[i], i);
            return build(preorder, 0, inorder.length - 1);
        }
    
        private TreeNode build(int[] preorder, int lo, int hi) {   // the subtree whose inorder is inorder[lo..hi]
            if (lo > hi) return null;
            TreeNode root = new TreeNode(preorder[next++]);       // preorder gives the root first
            int mid = where.get(root.val);                        // left of it in inorder is the left subtree
            root.left = build(preorder, lo, mid - 1);
            root.right = build(preorder, mid + 1, hi);
            return root;
        }
    }

    C++

    class Solution {
    public:
        int next;                                   // the next preorder value to place
        unordered_map<int, int> where;              // value -> its index in inorder
    
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            next = 0;
            where.clear();
            for (int i = 0; i < static_cast<int>(inorder.size()); i++) where[inorder[i]] = i;
            return build(preorder, 0, static_cast<int>(inorder.size()) - 1);
        }
    
        TreeNode* build(vector<int>& preorder, int lo, int hi) {   // the subtree whose inorder is inorder[lo..hi]
            if (lo > hi) return NULL;
            TreeNode* root = new TreeNode(preorder[next++]);      // preorder gives the root first
            int mid = where[root->val];                           // left of it in inorder is the left subtree
            root->left = build(preorder, lo, mid - 1);
            root->right = build(preorder, mid + 1, hi);
            return root;
        }
    };

    Python

    from lib import TreeNode
    
    
    class Solution:
        def buildTree(self, preorder: list[int], inorder: list[int]):
            where = {v: i for i, v in enumerate(inorder)}   # value -> its index in inorder
            it = iter(preorder)                     # preorder gives each root before its subtrees
    
            def build(lo, hi):                      # the subtree whose inorder is inorder[lo..hi]
                if lo > hi:
                    return None
                root = TreeNode(next(it))
                mid = where[root.val]               # left of it in inorder is the left subtree
                root.left = build(lo, mid - 1)
                root.right = build(mid + 1, hi)
                return root
    
            return build(0, len(inorder) - 1)

    Common mistakes

    • Building the right subtree first.
    • Searching inorder linearly each time.

    Similar problems