-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecover_binary_search_tree.cc
45 lines (40 loc) · 2.47 KB
/
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
// In-order to travel the tree. Find first node which is bigger then the just
// right one; second node which is smaller then the left one; exchage the first
// and the second.
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void recoverTree(TreeNode *root) {
visitTree(root);
int tmp;
tmp = first_abnormal->val;
first_abnormal->val = second_abnormal->val;
second_abnormal->val = tmp;
}
private:
TreeNode *first_abnormal, *second_abnormal;
TreeNode *node1, *node2;
void visitTree(TreeNode *node) {
if (NULL == node) return;
visitTree(node->left);
node1 = node2;
node2 = node;
if (NULL != node1) {
if (node1->val > node2->val) {
if (NULL == first_abnormal) {
first_abnormal = node1;
second_abnormal = node2;
} else second_abnormal = node2;
}
}
visitTree(node->right);
}
};