Concise c++ recursive solution (17 lines)


  • 0
    L
    class Solution {
    public:
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            if (preorder.empty() || inorder.empty()) return nullptr;
            unordered_map<int, int> umap;
            for (int i = 0; i < inorder.size(); ++i) umap[inorder[i]] = i;
            return buildCore(preorder, 0, preorder.size()-1, inorder, 0, inorder.size()-1, umap);
        }
        
        TreeNode* buildCore(vector<int>& preorder, int pl, int pr, vector<int>& inorder, int il, int ir, unordered_map<int, int>& umap) {
            if (pl > pr) return nullptr; 
            TreeNode* root = new TreeNode(preorder[pl]);
            int i = umap[preorder[pl]];
            root->left = buildCore(preorder, pl + 1, pl + i - il, inorder, il, i - 1, umap);
            root->right = buildCore(preorder, pl + i - il + 1, pr, inorder, i + 1, ir, umap);
            return root;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.