105. Construct Binary Tree from Preorder and Inorder Traversal

1. Description

Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree and inorder is the inorder traversal of the same tree, construct and return the binary tree.

2. Example

Example 1

Example 1
Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2

Input: preorder = [-1], inorder = [-1]
Output: [-1]

3. Constraints

  • 1 <= preorder.length <= 3000
  • inorder.length == preorder.length
  • -3000 <= preorder[i], inorder[i] <= 3000
  • preorder and inorder consist of unique values.
  • Each value of inorder also appears in preorder.
  • preorder is guaranteed to be the preorder traversal of the tree.
  • inorder is guaranteed to be the inorder traversal of the tree.

4. Solutions

Recursion

n = preorder.size()
Time complexity: O(n)
Space complexity: O(n)

class Solution {
public:
    TreeNode *buildTree(const vector<int> &preorder, const vector<int> &inorder) {
        const int n = preorder.size();
        for (int i = 0; i < n; ++i) {
            value_index[inorder[i]] = i;
        }

        return build_tree(preorder, 0, n, 0, n);
    }

private:
    unordered_map<int, int> value_index;
    TreeNode *build_tree(
        const vector<int> &preorder,
        int pre_left,
        int pre_right,
        int in_left,
        int in_right) {
        if (pre_left == pre_right) {
            return nullptr;
        }

        int root_value = preorder[pre_left];
        TreeNode *root = new TreeNode(root_value);
        int index = value_index[root_value];

        root->left =
            build_tree(preorder, pre_left + 1, pre_left + 1 + (index - in_left), in_left, index);
        root->right =
            build_tree(preorder, pre_left + 1 + (index - in_left), pre_right, index + 1, in_right);

        return root;
    }
};
comments powered by Disqus