Neat c++ solution


  • 0
    I
    TreeNode* help(vector<int>& inorder, vector<int>& preorder, int start, int end, int rootIdx) {
        if (start > end) return NULL;
        TreeNode *root = new TreeNode(preorder[rootIdx]);
        int pos = start;
        while (inorder[pos] != preorder[rootIdx]) pos++;
        root->left = help(inorder, preorder, start, pos - 1, rootIdx + 1);
        root->right = help(inorder, preorder, pos + 1, end, rootIdx + 1 + pos - start);
        return root;
    }
    
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        return inorder.empty() ? NULL : help(inorder, preorder, 0, inorder.size() - 1, 0);
    }

Log in to reply
 

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