-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab6_4.cpp
117 lines (108 loc) · 1.97 KB
/
lab6_4.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
106
107
108
109
110
111
112
113
114
115
116
117
// lab6_4.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include <stdlib.h>
using namespace std;
int get_elem();
struct Tree
{
Tree* p_left;
Tree* p_mid;
Tree* p_right;
int n;
};
Tree* MakeElements(int N)
{
if (N == 0)
{
return NULL;
}
Tree* p_mid = new Tree;
p_mid->n = 1;
N--;
p_mid->p_mid = NULL;
if (N == 0)
{
p_mid->p_left = NULL;
p_mid->p_right = NULL;
}
else
{
Tree* p_left = p_mid->p_left = new Tree;
p_left->n = 2;
p_left->p_left = NULL;
p_left->p_right = NULL;
N--;
if (N == 0)
{
p_left->p_mid = NULL;
p_mid->p_right = NULL;
}
else
{
Tree* p_right = p_mid->p_right = new Tree;
p_right->n = 3;
p_right->p_left = NULL;
p_right->p_right = NULL;
N--;
if (N == 0)
{
p_right->p_mid = NULL;
}
else
{
p_left->p_mid = p_right->p_mid = MakeElements(N);
}
}
}
return p_mid;
}
void PrintTree(Tree* root);
int main()
{
const int count_elements = get_elem();
Tree* root = MakeElements(count_elements);
PrintTree(root);
return 0;
}
void PrintTree(Tree* p_mid)
{
if (p_mid != NULL)
{
cout << " " << p_mid->n << endl;
if (p_mid->p_left != NULL)
{
Tree* p_left = p_mid->p_left;
cout << " " << p_left->n;
}
if (p_mid->p_right != NULL)
{
Tree* p_right = p_mid->p_right;
cout << " " << p_right->n << endl;
if (p_right->p_mid != NULL)
{
PrintTree(p_right->p_mid);
}
}
}
}
int get_elem()
{
int elem = 0;
while (true)
{
cout << "How many elements u need in tree?\n";
cin >> elem;
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
cout << "It's not correct, please write again" << endl;
}
else
{
return elem;
break;
}
}
}