forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 14
/
recover-binary-search-tree.cpp
59 lines (56 loc) · 1.57 KB
/
recover-binary-search-tree.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
// Time: O(n)
// Space: O(1)
/**
* 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) {
MorrisTraversal(root);
}
private:
void MorrisTraversal(TreeNode *root) {
if (!root) {
return;
}
pair<TreeNode *, TreeNode *> broken;
TreeNode *prev = nullptr;
TreeNode *cur = root;
while (cur) {
if (!cur->left) {
detect(prev, cur, &broken);
prev = cur;
cur = cur->right;
} else {
TreeNode *node = cur->left;
while (node->right && node->right != cur) {
node = node->right;
}
if (!node->right) {
node->right = cur;
cur = cur->left;
} else {
detect(prev, cur, &broken);
prev = cur;
node->right = nullptr;
cur = cur->right;
}
}
}
swap(broken.first->val, broken.second->val);
}
void detect(TreeNode *prev, TreeNode *cur, pair<TreeNode *, TreeNode *> *broken) {
if (prev && prev->val > cur->val) {
if (!broken->first) { // Find the first broken node.
broken->first = prev;
}
broken->second = cur; // Find the last broken node.
}
}
};