-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathLeetcode_recover-binary-search-tree.cc
77 lines (76 loc) · 1.7 KB
/
Leetcode_recover-binary-search-tree.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* 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*lastNode = NULL, *sw1 = NULL, *sw2 = NULL;
void in_order_tra(TreeNode* root)
{
if(root->left)
in_order_tra(root->left);
if(lastNode)
{
if(lastNode->val > root->val)
{
if(!sw1)
{
sw1 = lastNode;
sw2 = root;
}
else
{
sw2 = root;
return;
}
}
}
lastNode = root;
if(root->right)
in_order_tra(root->right);
}
void recoverTree(TreeNode *root) {
if(!root)
return;
in_order_tra(root);
if(sw1 && sw2)
swap(sw1->val, sw2->val);
}
};
//Second trial, almost the same
class Solution {
private:
TreeNode*p1, *p2, *last;
void inOrder(TreeNode *root) {
if(root->left)
inOrder(root->left);
if(last) {
if(last->val > root->val) {
if(!p1) {
p1 = last;
p2 = root;
} else {
p2 = root;
return;
}
}
}
last = root;
if(root->right)
inOrder(root->right);
}
public:
void recoverTree(TreeNode *root) {
if(!root)
return;
last = p1 = p2 = NULL;
inOrder(root);
if(p1 && p2)
swap(p1->val, p2->val);
}
};