/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ classSolution { public: TreeNode *first, *second; //store the position that needs to be swap TreeNode *prev; // store the previous position in tree voidrecoverTree(TreeNode* root){ first = second = prev = NULL; //inorder traversal dfs(root); if (first != NULL && second != NULL) { int tmp = first -> val; first -> val = second -> val; second -> val = tmp; } } voiddfs(TreeNode* root){ // check left first if (root -> left != NULL) dfs(root -> left); // if there's any disorder, store the position. if (prev != NULL && prev -> val > root -> val) { if (first == NULL) first = prev; if (first != NULL) second = root; } // current root become prev prev = root; // right subtree if (root -> right != NULL) dfs(root -> right); } };
time complexity: $O(n)$ space complexity: $O(logn)$