Posted on

Description

Submission

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
    TreeNode* first = nullptr;
    TreeNode* second = nullptr;
    TreeNode* prev = nullptr;
    TreeNode* tmp = nullptr;

    void inOrder(TreeNode* cur) {
        if(cur == nullptr) return;

        inOrder(cur->left);

        if(prev && prev->val > cur->val) {
            if(!first && !tmp) {
                first = prev;
                tmp = cur;
            } else {
                second = cur;
            }
        }
        prev = cur;

        inOrder(cur->right);
    }
public:
    void recoverTree(TreeNode* root) {
        inOrder(root);
        if(!second) {
            swap(first->val, tmp->val);
        } else {
            swap(first->val, second->val);
        }
    }
};

Leave a Reply

Your email address will not be published. Required fields are marked *