Complete-Preparation

🎉 One-stop destination for all your technical interview Preparation 🎉

View the Project on GitHub

105. Construct Binary Tree from Preorder and Inorder Traversal 🌟🌟

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.

Solution

105-leetcode

code

class Solution {
    TreeNode* buildTreeHelp(vector<int>& preorder, vector<int>& inorder, int& rootIndex, int inStart, int inEnd, map<int, int>& inorderMap)
    {
        if (rootIndex >= preorder.size() || inStart > inEnd)
            return NULL;
        TreeNode* root = new TreeNode(preorder[rootIndex]);
        int inorderIndex = inorderMap[preorder[rootIndex]]; // optimized with map
        rootIndex++; // Increase rootIndex

        // (inStart, inorderIndex - 1), (inorderIndex + 1, inEnd) = leftSubtree, rightSubtree
        root->left = buildTreeHelp(preorder, inorder, rootIndex, inStart, inorderIndex - 1, inorderMap);
        root->right = buildTreeHelp(preorder, inorder, rootIndex, inorderIndex + 1, inEnd, inorderMap);

        return root;
    }

public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
    {
        map<int, int> inMap;
        for (int i = 0; i < inorder.size(); i++) {
            inMap[inorder[i]] = i;
        }
        int inStart = 0, inEnd = inorder.size() - 1, rootIndex = 0;
        TreeNode* root = buildTreeHelp(preorder, inorder, rootIndex, inStart, inEnd, inMap);
        return root;
    }
};