-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathzad11_ms.cpp
105 lines (94 loc) · 1.92 KB
/
zad11_ms.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <queue>
using namespace std;
typedef struct node *bin_tree;
struct node
{
int val;
bin_tree left, right;
};
bin_tree newNode(int val)
{
bin_tree newTree = (bin_tree)malloc((sizeof(int) + 2 * sizeof(bin_tree)));
newTree->val = val;
return newTree;
}
bin_tree bestify(bin_tree t, queue<bin_tree> *toAdd)
{
if (!t)
return t;
// if empty put
if (!t->left)
{
if (!toAdd->empty() && toAdd->front()->val < t->val)
{
t->left = toAdd->front();
toAdd->pop();
}
}
if (!t->right)
{
if (!toAdd->empty() && toAdd->front()->val > t->val)
{
t->right = toAdd->front();
toAdd->pop();
}
}
if (t->left)
{
if (t->left->val > t->val)
{
if (t->right != NULL)
{
toAdd->push(t->right);
}
t->right = t->left;
t->left = NULL;
}
else
{
t->left = bestify(t->left, toAdd);
}
}
if (t->right)
{
if (t->right->val < t->val)
{
toAdd->push(t->right);
t->right = NULL;
}
else
{
t->right = bestify(t->right, toAdd);
}
}
return t;
}
bin_tree bestify(bin_tree t)
{
queue<bin_tree> q;
bin_tree r = NULL;
do
{
r = bestify(t, &q);
} while (!q.empty());
return r;
}
int main()
{
bin_tree t = newNode(1);
t->left = newNode(2);
t->left->left = newNode(4);
t->left->left->left = newNode(5);
t->right = newNode(3);
t->right->left = newNode(6);
t->right->right = newNode(7);
t->left->right = newNode(11);
t->right->left->right = newNode(12);
// bin_tree t = newNode(2);
// t->left = newNode(4);
// t->left->right = newNode(5);
// t->right = newNode(11);
bestify(t);
return 0;
}