-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathLeetCode#118.cc
More file actions
60 lines (53 loc) · 1.33 KB
/
LeetCode#118.cc
File metadata and controls
60 lines (53 loc) · 1.33 KB
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
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
TreeNode* n1;
TreeNode* n2;
TreeNode* prev;
void dfs(TreeNode* root){
if(root->left==NULL && root->right==NULL){
if(prev && root->val < prev->val){
if(n1==NULL){
n1 = prev;n2=root;
}
else{
n2 = root;
}
}
prev = root;
return ;
}
if(root->left) dfs(root->left);
if(prev && root->val < prev->val){
if(n1==NULL){
n1 = prev;n2=root;
}
else{
n2 = root;
}
}
prev = root;
if(root->right) dfs(root->right);
}
public:
void recoverTree(TreeNode *root) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
n1 = n2 = NULL;
prev = NULL;
dfs(root);
if(n1){
int tmp = n1->val;
n1->val = n2->val;
n2->val = tmp;
}
}
};