leetcode 99. 恢复二叉搜索树
题目
修正二叉搜索树中两个互换的元素
思路
利用二叉搜索树中序遍历就是递增序列的特点 , 找到对应值
而二叉搜索树中值唯一 , 对应可以找到节点并交换
代码
class Solution {
public:
vector<int> v;
void inorder(TreeNode* root)
{
if(!root)
{
return ;
}
inorder(root->left);
v.push_back(root->val);
inorder(root->right);
}
void update(TreeNode* root,int x,int y,int cnt)
{
if(!root)
return ;
if(root->val == x)
{
root->val = y;
cnt--;
if(!cnt)
return ;
}
else if(root->val == y)
{ root->val = x;
cnt--;
if(!cnt)
return ;
}
update(root->left,x,y,cnt);
update(root->right,x,y,cnt);
}
void recoverTree(TreeNode* root) {
inorder(root);
int x,y;
bool f =false;
for(int i = 0; i< v.size()-1; i++)
{
if(v[i] > v[i+1])
{
if(!f)
{
f = true;
x = v[i],y=v[i+1];
}
else{
y = v[i+1];
}
}
}
update(root,x,y,2);
}
};

浙公网安备 33010602011771号