您的位置:首页 > 编程语言 > C语言/C++

Recover Binary Search Tree leetcode c++

2014-11-14 16:23 423 查看
this problem have two situations.

1.when we traversal the whole binary search tree, if we just got one pair of value that the pre's value > root'sval

it means that two mistakes are adjacent.

2.if we got two, we just need to exchange the value of them.

Please see my code below./**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode *last;
TreeNode *mistak1;
TreeNode *mistak2;
bool first = true;

void dfs(TreeNode *root)
{
if(root == NULL)
return ;
if(root->left)
dfs(root->left);
if(first)
{
last = root;
first = false;
}
else
{

if(root->val < last->val)
if(mistak1!= NULL)
mistak2 = root;
else
{
mistak1 = last;
mistak2 = root;
}
last = root;
}
if(root->right)
dfs(root->right);
}

void recoverTree(TreeNode *root) {
dfs(root);
if(mistak1!= NULL && mistak2!= NULL)
{
int temp;
temp = mistak1->val;
mistak1->val = mistak2->val;
mistak2->val = temp;
}
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: