Simple 8 lines recursive c++ code which beats 94.55%


  • 0
    S
    TreeNode* AddNode(vector<int>& inorder, vector<int>& postorder, int inleft, int inright, int postroot){
        if(inleft > inright) return NULL;
        
        TreeNode* root = new TreeNode(postorder[postroot]);
        
        int inroot = inright;
        while(inorder[inroot] != postorder[postroot]) inroot--;
        
        root->left = AddNode(inorder, postorder, inleft, inroot - 1, postroot - (inright - inroot) - 1);
        root->right = AddNode(inorder, postorder, inroot + 1, inright, postroot - 1 );
        
        return root;
    }
    
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        return AddNode(inorder, postorder, 0, inorder.size() - 1, postorder.size() - 1);
    }

Log in to reply
 

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