106. Construct Binary Tree from Inorder and Postorder Traversal

1. Description

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

2. Example

Example 1

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]

3. Constraints

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

4. Solutions

Recursion

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

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

        return build_tree(postorder.rbegin(), postorder.rend(), 0, n);
    }

private:
    unordered_map<int, int> value_index;
    TreeNode *build_tree(
        vector<int>::const_reverse_iterator post_left,
        vector<int>::const_reverse_iterator post_right,
        int in_left,
        int in_right) {
        if (post_left == post_right) {
            return nullptr;
        }

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

        root->right =
            build_tree(post_left + 1, post_left + (in_right - index), index + 1, in_right);
        root->left = build_tree(post_left + (in_right - index), post_right, in_left, index);

        return root;
    }
};
comments powered by Disqus