My simple c++ solution


  • 0
    K
    class Solution {
    public:
    void helper(TreeNode * root, TreeNode *& first, TreeNode* &second, TreeNode *& parent)
    {
        if(!root)return;
        helper(root->left, first, second, parent);
            if(parent && root->val<parent->val){
                if(!first)first = parent;
                second = root;
            }
        parent=root;
        helper(root->right, first, second, parent);
    }
    void recoverTree(TreeNode* root) {
        TreeNode * first=NULL, *second=NULL, *parent=NULL;
        helper(root, first, second, parent);
        int temp=first->val;
        first->val=second->val;
        second->val=temp;
    }
    

    };


Log in to reply
 

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