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;
}
}
};
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;
}
}
};
相关文章推荐
- leetcode_c++:树: Recover Binary Search Tree(099)
- LeetCode: Recover Binary Search Tree
- [Leetcode] Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- LeetCode -- Recover Binary Search Tree 详细解答
- [LeetCode] Recover Binary Search Tree
- leetcode Recover Binary Search Tree
- [leetcode刷题系列]Recover Binary Search Tree
- LeetCode 99: Recover Binary Search Tree
- LeetCode: Recover Binary Search Tree
- LeetCode-Recover Binary Search Tree
- LeetCode: Recover Binary Search Tree
- leetcode--Recover Binary Search Tree*
- LeetCode - Recover Binary Search Tree
- 【Leetcode】Recover Binary Search Tree
- LeetCode -- Recover Binary Search Tree
- LeetCode:Recover Binary Search Tree
- [Leetcode]Recover Binary Search Tree
- [LeetCode] Recover Binary Search Tree 解题报告
- [leetcode]Recover Binary Search Tree