-
Notifications
You must be signed in to change notification settings - Fork 38
/
Copy pathsolve.cpp
86 lines (86 loc) · 1.77 KB
/
solve.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
79
80
81
82
83
84
85
86
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr){}
};
class Solution {
public:
void flatten(TreeNode *root) {
slowFlatten(root);
}
private:
void slowFlatten(TreeNode *root) {
if (root == nullptr)
return ;
flatten(root->left);
flatten(root->right);
if (root->right == nullptr) {
root->right = root->left;
root->left = nullptr; // 不能少这个,否则RE
return;
}
TreeNode *p = root->left;
if (p) {
while (p->right) {
p = p->right;
}
p->right = root->right;
root->right = root->left;
}
root->left = nullptr;
}
void fastFlatten(TreeNode *root) {
while (root) {
if (root->left) {
TreeNode *left = root->left;
while (left->right) left = left->right;
left->right = root->right;
root->right = root->left;
root->left = nullptr;
}
root = root->right;
}
}
};
TreeNode *mk_node(int val)
{
return new TreeNode(val);
}
TreeNode *mk_child(TreeNode *root, TreeNode *left, TreeNode *right)
{
root->left = left;
root->right = right;
return root;
}
TreeNode *mk_child(TreeNode *root, int left, int right)
{
return mk_child(root, new TreeNode(left), new TreeNode(right));
}
TreeNode *mk_child(int root, int left, int right)
{
return mk_child(new TreeNode(root), new TreeNode(left), new TreeNode(right));
}
void print_list(TreeNode *root)
{
TreeNode *p = root;
while (p) {
cout << p->val << " ";
p = p->right;
}
cout << endl;
}
int main(int argc, char **argv)
{
Solution solution;
TreeNode *root = mk_child(mk_node(1), nullptr, mk_node(2));
//mk_child(root->left, 3, 4);
//mk_child(root->right, nullptr, mk_node(6));
solution.flatten(root);
print_list(root);
return 0;
}