106. Construct Binary Tree from Inorder and Postorder Traversal

Problem Statement

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.

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]

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.

Intuition

Approach:

Recursively build a Tree stiver video

https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/description/

https://www.youtube.com/watch?v=LgLRTaEMRVc&ab_channel=takeUforward

Approach 1:

C++
class Solution {
public:
    unordered_map<int,int> mp;
    TreeNode* Tree(vector<int>& postorder, int p_start, int p_end, vector<int>& inorder, int in_start, int in_end) {
        if(p_start > p_end or in_start > in_end)
            return nullptr;

        TreeNode* root = new TreeNode(postorder[p_start]);
        int index = mp[postorder[p_start]];
        int diff = in_end - index;

        root->left = Tree(postorder, p_start+diff+1, p_end, inorder, in_start, index-1);
        root->right = Tree(postorder, p_start+1, p_start+diff, inorder, index+1, in_end);

        return root;
    }

    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        for(int i=0; i<inorder.size(); i++)
            mp[inorder[i]] = i;
        
        reverse(postorder.begin(), postorder.end());

        return Tree(postorder, 0, postorder.size()-1, inorder, 0, inorder.size()-1);
    }
};

Approach 2:

C++

Approach 3:

C++

Approach 4:

C++

Similar Problems

Last updated