要求:两个数调换了,要恢复
思路:中序,可以用数组记录再遍历全部修改。也可以遍历时记下两个异序节点交换他们的值即可。空间O(1)要morris排序
/**
* 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 {
public:
TreeNode *t1, *t2, *pre;
void recoverTree(TreeNode* root) {
inorder(root);
int temp = t1->val;
t1->val = t2->val;
t2->val = temp;
}
void inorder(TreeNode *root){ //一次违反是两次违反的问题
if (root == NULL) return ;
inorder(root->left);
if (pre != NULL && pre->val > root->val) {
if (t1 == NULL) t1 = pre; //保证只给t1赋值一次
t2 = root;
}
pre = root;
inorder(root->right);
}
};