恢复二叉搜索树
题目
二叉搜索树中的两个节点被错误地交换。
请在不改变其结构的情况下,恢复这棵树。
示例
示例 1:
输入: [1,3,null,null,2]
1
/
3
2
输出: [3,1,null,null,2]
3
/
1
2
示例 2:
输入: [3,1,4,null,null,2]
3
/
1 4
/
2
输出: [2,1,4,null,null,3]
2
/
1 4
/
3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/recover-binary-search-tree
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
何为二叉搜索树?
二叉查找树(Binary Search Tree),(又:二叉搜索树,二叉排序树)它或者是一棵空树,或者是具有下列性质的二叉树:
若它的左子树不空,则左子树上所有结点的值均小于它的根结点的值; 若它的右子树不空,则右子树上所有结点的值均大于它的根结点的值;
它的左、右子树也分别为二叉排序树。
可以知道在中序遍历的情况下,是升序的。那么思路就有了,把树用中序遍历后,再进行排序,再次进行中序遍历,与sort之后的值进行比对,不等时进行值的交换。
代码
/**
* 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:
vector<int>res;
vector<int>temp;
int now1=INT_MIN;
int now2=INT_MIN;
TreeNode*p1=NULL;
TreeNode*p2=NULL;
//中序遍历
void inorder(TreeNode *now)
{
if(now)
{
inorder(now->left);
res.push_back(now->val);
inorder(now->right);
}
}
void find(TreeNode *now)
{
if(now!=NULL)
{
find(now->left);
if(now->val==now1)
{
p1=now;
}
if(now->val==now2)
{
p2=now;
}
find(now->right);
}
}
void recoverTree(TreeNode* root)
{
inorder(root);
temp=res;
sort(temp.begin(),temp.end());
for(int i=0;i<temp.size();i++)
{
if(temp[i]!=res[i])
{
if(now1==INT_MIN)
now1=temp[i];
else if(now2==INT_MIN)
{
now2=temp[i];
break;
}
}
}
find(root);
p1->val=now2;
p2->val=now1;
}
};