-
Notifications
You must be signed in to change notification settings - Fork 980
/
solution.h
28 lines (26 loc) · 844 Bytes
/
solution.h
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
#include <cstddef>
#include <algorithm>
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
void InorderTraversal(TreeNode *root, TreeNode **prev, TreeNode **first, TreeNode **second) {
if (root == NULL) return;
InorderTraversal(root->left, prev, first, second);
if (*prev && (*prev)->val > root->val) {
if (*first == NULL) *first = *prev;
*second = root;
}
*prev = root;
InorderTraversal(root->right, prev, first, second);
}
public:
void recoverTree(TreeNode *root) {
TreeNode *prev = NULL, *first = NULL, *second = NULL;
InorderTraversal(root, &prev, &first, &second);
if (first && second) std::swap(first->val, second->val);
}
};