leetcode99
题目简介
二叉搜索树中的两个节点被错误的交换,我们需要将它换回来
示例 1:
输入:[1,3,null,null,2]
输出: [3,1,null,null,2]
示例 2:
输入: [3,1,4,null,null,2]
输出: [2,1,4,null,null,3]
题目思想
我们可以用中序遍历来找到错误的节点,因为只有两个节点是错误的,所以我们只需要用两个类内公共变量来存储这个,并且利用中序遍历从小到大的特性,找出那个位置不对的值和可以拿来交换的值
AC代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *t1,*t2,*pre;
bool judge;
int tmp;
void recoverTree(TreeNode* root) {
find(root);
tmp=t1->val;
t1->val=t2->val;
t2->val=tmp;
}
void find(TreeNode *root){
if(root==NULL){
return;
}
find(root->left);
if(pre!=NULL&&root->val<pre->val&&judge==0){
judge=1;
t1=root;
t2=pre;
}
else if(pre!=NULL&&root->val<pre->val&&judge==1){
t1=root;
}
pre=root;
find(root->right);
}
};
注:其中的judge是用来防止pre变量和root一起改变,因为root是顺序遍历下去需要先遍历到左子树,如果pre一起改变的话会导致用来交换的值是目标值的父结点