C++ solution which beats 100% solution with in-place method


  • 0
    S

    The recursive method to solve this problem.

    This method is adapted from pre-order. Pre-order is left-root-right, but I change it to right-root-left to satisfy the requirement to store the accumulated result in last.

    class Solution {
    public:
        int last = 0;
        void findRightSum(TreeNode* root) {
            if(!root) return;
            if(root->right) findRightSum(root->right);
            root->val += last;
            last = root->val;  
            if(root->left)  findRightSum(root->left);
        }
        
        TreeNode* convertBST(TreeNode* root) {
            if(!root) 
                return root;
            findRightSum(root);
            return root;
        }
    };
    

Log in to reply
 

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