105. Construct Binary Tree from Preorder and Inorder Traversal

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
private:
    int rootIndex = 0;
    unordered_map<int, int> indexMap;
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder)
    {
        int n = preorder.size();

        for(int i = 0; i < n; ++i)
        {
            indexMap[inorder[i]] = i;
        }
        return build(preorder, 0, n - 1);
    }

    TreeNode* build(vector<int>& preorder, int left, int right)
    {
        if(left > right) return nullptr;

        int rootValue = preorder[rootIndex++];

        TreeNode* root = new TreeNode(rootValue);

        root->left = build(preorder, left, indexMap[rootValue] - 1);

        root->right = build(preorder, indexMap[rootValue] + 1, right);
        return root;
    }
};
  • T: O(N)O(N)
  • S: O(N)O(N)