-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path99.cpp
More file actions
30 lines (29 loc) · 656 Bytes
/
Copy path99.cpp
File metadata and controls
30 lines (29 loc) · 656 Bytes
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
TreeNode *prev = 0, *t1 = 0, *t2 = 0;
void check(TreeNode *root) {
if (!root) return;
check(root->left);
if (prev && prev->val > root->val) {
if (!t1) t1 = prev;
t2 = root;
}
prev = root;
check(root->right);
}
public:
void recoverTree(TreeNode* root) {
check(root);
if (t1 && t2) {
swap(t1->val, t2->val);
}
}
};