-
Notifications
You must be signed in to change notification settings - Fork 77
/
solution.cpp
45 lines (41 loc) · 913 Bytes
/
solution.cpp
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
/**
* 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 *node1;
TreeNode *node2;
TreeNode *pre;
void recoverTree(TreeNode *root)
{
node1 = node2 = pre = NULL;
findout(root);
swap(node1->val, node2->val);
return;
}
void findout(TreeNode *root)
{
if (root->left != NULL)
findout(root->left);
if (pre != NULL)
{
if (pre->val > root->val)
{
if (node1 == NULL)
node1 = pre, node2 = root;
else
node2 = root;
}
}
pre = root;
if (root->right != NULL)
findout(root->right);
}
};