Accepted recursive solution in C++


  • 0
    J
    class Solution {
    TreeNode* previous = new TreeNode(INT_MIN);
    TreeNode* target1 = NULL;
    TreeNode* target2 = NULL;
    public:
    void recoverTree(TreeNode* root) {
        if(root  == NULL) return;
        helper(root);
        int temp = target2->val;
        target2->val = target1->val;
        target1->val = temp;
        return;
    }
    void helper(TreeNode* root)
    {
        if(!root) return;
        helper(root->left);
        if(root->val < previous->val)
        {
            if(target1 == NULL)
            {
                target1  = previous;
                target2 = root;
                previous = root;
            }
            else 
            {
                target2 = root;
                previous = root;
            }
        }
        else
        {
            previous = root;
        }
        helper(root->right);
    }
    

    };


Log in to reply
 

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