forked from illuz/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAC_threaded_binary_tree_n.cpp
79 lines (68 loc) · 1.86 KB
/
AC_threaded_binary_tree_n.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* Author: illuz <iilluzen[at]gmail.com>
* File: AC_threaded_binary_tree_n.cpp
* Create Date: 2015-03-08 23:51:26
* Descripton: Use the Threaded Binary Tree presented by Morris.
*/
#include <bits/stdc++.h>
using namespace std;
const int N = 0;
// 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) {
TreeNode *f1 = NULL, *f2 = NULL;
TreeNode *cur, *pre, *pre_o;
if (!root)
return;
bool found = false;
cur = root;
while (cur) {
if (!cur->left) {
// begin
if (pre_o && pre_o->val > cur->val) {
if (!found) {
f1 = pre_o;
found = true;
}
f2 = cur;
}
pre_o = cur;
// end
cur = cur->right;
} else {
pre = cur->left;
while (pre->right && pre->right != cur)
pre = pre->right;
if (!pre->right) {
pre->right = cur;
cur = cur->left;
} else {
pre->right = NULL;
// begin
if (pre_o && pre_o->val > cur->val) {
if (!found) {
f1 = pre_o;
found = true;
}
f2 = cur;
}
pre_o = cur;
// end
cur = cur->right;
}
}
}
if (f1 && f2)
swap(f1->val, f2->val);
}
};
int main() {
return 0;
}