C++ Recursion 13 lines


  • 0
    TreeNode* buildhelp (vector<int>& inorder, int il, int ir, vector<int>& postorder, int pl, int pr) {
        if (il > ir) return NULL;
        TreeNode* root = new TreeNode(postorder[pr]);
        int ind;
        for (int i=0; i<ir-il+1; i++)
            if(inorder[il+i]==root->val) ind = i;
        root->left = buildhelp(inorder, il, il+ind-1, postorder, pl, pl+ind-1);
        root->right = buildhelp(inorder, il+ind+1, ir, postorder, pl+ind, pr-1);
        return root;
    }
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return buildhelp(inorder, 0, inorder.size()-1, postorder, 0, postorder.size()-1);
    }

Log in to reply
 

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