C++ code, easy to understand

  • 0
        TreeNode* recursive(const vector<int>& preorder, const vector<int>& inorder)
                return NULL;
            TreeNode *p = new TreeNode(preorder[0]);
            auto idx = find(inorder.begin(), inorder.end(), preorder[0]);
            p->left = recursive(vector<int>(preorder.begin()+1, preorder.begin()+(idx-inorder.begin()+1)), vector<int>(inorder.begin(), idx));
            p->right = recursive(vector<int>(preorder.begin()+(idx-inorder.begin()+1), preorder.end()), vector<int>(idx+1, inorder.end()));
            return p;
        TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
            return recursive(preorder, inorder);

Log in to reply

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