-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtree.cpp
More file actions
112 lines (96 loc) · 2.13 KB
/
tree.cpp
File metadata and controls
112 lines (96 loc) · 2.13 KB
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
106
107
108
109
110
111
112
#include "tree.h"
tree::tree() {
key = -1;
left = right = 0;
balance = 1;
}
int tree::Height(tree* root) {
if (root == NULL) return 0;
int hLeft = Height(root->left),
hRight = Height(root->right);
if (hLeft > hRight) return hLeft + 1;
else
return hRight + 1;
}
void tree::SetBalance(tree* (&root)) {
if (root != NULL)
root->balance = Height(root->right) - Height(root->left);
}
void tree::TurnLeft(tree* (&root)) {
tree* rightSubtree, * rightSubtreeLeftSubtree;
rightSubtree = root->right;
rightSubtreeLeftSubtree = rightSubtree->left;
rightSubtree->left = root;
root->right = rightSubtreeLeftSubtree;
root = rightSubtree;
SetBalance(root->left);
SetBalance(root);
}
void tree::TurnRight(tree* (&root)) {
tree* leftSubtree, * leftSubtreeRightSubtree;
leftSubtree = root->left;
leftSubtreeRightSubtree = leftSubtree->right;
leftSubtree->right = root;
root->left = leftSubtreeRightSubtree;
root = leftSubtree;
SetBalance(root->right);
SetBalance(root);
}
void tree::Insert(tree* (&root), int d) {
if (root == NULL) {
root = new tree;
root->key = d;
root->balance = 0;
root->left = NULL;
root->right = NULL;
}
else {
if (d > root->key) {
Insert(root->right, d);
if (Height(root->right) - Height(root->left) > 1) {
if (Height(root->right->right) < Height(root->right->left))
TurnRight(root->right);
TurnLeft(root);
}
}
else
if (d < root->key) {
Insert(root->left, d);
if(Height(root->left) - Height(root->right) > 1) {
if (Height(root->left->left) < Height(root->left->right))
TurnLeft(root->left);
TurnRight(root);
}
}
SetBalance(root);
}
}
void tree::Output(tree* p) {
if (p != NULL) {
Output(p->left);
cout << p->key << " ";
Output(p->right);
}
}
void tree::Print(tree* p) {
cout << endl;
cout << "Ðàñïå÷àòêà äåðåâà â ñèììåòðè÷åñêîì ïîðÿäêå: " << endl;
for (int k = 1; k <= 95; k++) {
cout << "-";
}
cout << endl;
p->Output(p);
cout << endl;
for (int k = 1; k <= 95; k++) {
cout << "-";
}
cout << endl;
}
void tree::Clear(tree** p) {
if ((*p) != NULL) {
Clear(&(*p)->left);
Clear(&(*p)->right);
delete* p;
*p = NULL;
}
}