106. Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]

Return the following binary tree:

    3
   / \
  9  20
    /  \
   15   7
TreeNode* build(vector<int>& inorder, int iLeft, int iRight, vector<int>& postorder, int pLeft, int pRight,
                unordered_map<int, int>& m) {
    if (iLeft > iRight || pLeft > pRight) return nullptr;
    TreeNode* cur = new TreeNode(postorder[pRight]);
    int i = m[postorder[pRight]]; // the root index in inorder traversal
    cur->left = build(inorder, iLeft, i - 1, postorder, pLeft, pLeft + i - iLeft - 1, m);
    cur->right = build(inorder, i + 1, iRight, postorder, pLeft + i - iLeft, pRight - 1, m);
    return cur;
}
TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) { // time: O(n); space: O(n)
    // record the corresponding index of numbers in inorder traversal
    unordered_map<int, int> m;
    for (int i = 0; i < inorder.size(); ++i) {
        m[inorder[i]] = i;
    }
    return build(inorder, 0, inorder.size() - 1, postorder, 0, postorder.size() - 1, m);
}
105. Construct Binary Tree from Preorder and Inorder Traversal

Last updated

Was this helpful?