Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Карта форума Темы раздела Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.76/21: Рейтинг темы: голосов - 21, средняя оценка - 4.76
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
1

Деревья

09.01.2014, 01:22. Показов 4206. Ответов 11
Метки нет (Все метки)

Author24 — интернет-сервис помощи студентам
Здравствуйте. Помогите разобраться с деревьями. Можно бинарное, можно не бинарное.
0
Programming
Эксперт
94731 / 64177 / 26122
Регистрация: 12.04.2006
Сообщений: 116,782
09.01.2014, 01:22
Ответы с готовыми решениями:

деревья
собственно написал программу на с++, которая выводит бинарное дерево. но почему на третьем узле...

Деревья
Знаю пару тройку фундаментальных структур на основе дерева: красно-черное дерево бинарное древо...

Деревья
Я не особо разбираюсь в программировании (т.к это не связано с моей будущей специальностью,но те...

деревья, с++
Реализовать функцию вычисления высоты дерева и либо-какого поддерева за указанием пользователя....

11
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
09.01.2014, 01:24 2
http://ru.wikipedia.org/wiki/Дерево

Добавлено через 39 секунд
По делу:
листок бумаги и карандаш в помощь. Ничего продуктивнее для понимания еще не придумали.
0
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
09.01.2014, 01:31  [ТС] 3
MrGluck, мне бы на коде объяснить, как с указателями это все, выделениями памяти и т.д.
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
09.01.2014, 01:34 4
C++
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
118
119
120
121
122
123
124
125
126
127
128
129
#include <iostream>
#include <conio.h>
#include <fstream>
using namespace std;
 
struct  bin_tree
{
   int value;
   bin_tree *left, *right;
}*pHead = NULL; // указатель на вершину равен нулю
 
// добавление конкретного узла дерева
void add_node(bin_tree*, int); 
// проверка на "пустоту" дерева, если указатель на вершину равен нулю, создает узел
void add_bin_tree(int);
// обход
void print(bin_tree*);
void traversal(bin_tree*, ofstream&);
int h_tree(bin_tree *);
 
int main()
{
    setlocale (LC_ALL, "Russian");
    int choose, el;
    cout<< "1. Загрузить последовательность с файла\n"
        << "2. Ввести последовательность вручную\n\n"
        << "Ваш выбор: ";
    do{ cin>> choose;} while(choose != 1 && choose != 2);
    if (choose == 1)
    {        
        ifstream iz("bin.txt");
        if (iz.bad()) return 1;
        while(!iz.eof() && iz>> el)
            add_bin_tree (el);     
        iz.close();
    }
    
    if (choose == 2)
    {
        cout<< "Информационные поля вершин дерева:\n";
        while(cin>> el)
            add_bin_tree (el);
    }
    ofstream o("bin.txt");
    print (pHead);
    traversal (pHead, o);
    getch();
    o.close();
    return 0;
}
 
void add_node(bin_tree* tree, int value) // добавление конкретного узла дерева
{
    if(value < tree->value)
    { 
        if(tree->left != NULL) // если значение меньше, двигаемся по "левой ветке"
            add_node(tree->left, value);
        else
        {  
            tree->left = new bin_tree;
            tree->left->value = value;
            tree->left->left = NULL;
            tree->left->right = NULL;
        }
    }
 
    if(value > tree->value) // иначе двигаемся по правой 
    { 
        if(tree->right != NULL)
            add_node(tree->right, value);
        else
        {
            tree->right = new bin_tree;
            tree->right->value = value;
            tree->right->left=NULL;
            tree->right->right=NULL;
        }
    }
 
    if(value == tree->value)                
        cout<< value<< " is already in tree"<< endl;
}
 
void add_bin_tree(int value)
{
    if(pHead == NULL) // если дерево пустое - создадим первый узел
    {
       pHead = new bin_tree;
       pHead->value = value;
       pHead->left = NULL;
       pHead->right = NULL;
    }
    else
        add_node(pHead, value); // если в вершине уже что-то есть - добавляем слева или справа 
}
 
void traversal(bin_tree* tree, ofstream &o)
{     
    if (tree != NULL)
    { 
        traversal(tree->left, o);
        o<< tree->value<< " ";
        traversal(tree->right, o);
    }
}
 
void print(bin_tree* tree)
{     
    if (tree != NULL)
    { 
        print(tree->left);
        cout<< tree->value<< " ";
        print(tree->right);
    }
}
 
int h_tree(bin_tree* tree)
{
     int h = 1, m = 0, s;
     if (tree == NULL)
        return 0;
     s = h_tree(tree->left);
     if (s > m)
         m = s;
     s = h_tree(tree->right);
     if (s > m)
         m = s;
     return h + m;
}
Здесь память не освобождается, по сути это должно делаться также рекурсивно в обратном порядке: с концов к началу.
2
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
09.01.2014, 01:36  [ТС] 5
MrGluck, для чего нужен
C++ (Qt)
1
setlocale (LC_ALL, "Russian");
?
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
09.01.2014, 01:37 6
устанавливает локаль дял работы с кириллицей. Чтобы русские символы воспринимало
0
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
09.01.2014, 01:39  [ТС] 7
MrGluck, логика создания дерева такая? Сначала создается корень, объявляется его структура, потом уже указателями двигаемся по памяти(обнуляем ячейки памяти потом заносим туда свои данные)?
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
09.01.2014, 01:41 8
Узел дерева содержит указатель на правое и левое поддерево. Если мы создаем новый узел - мы говорим, что правого и левого поддерева у него изначально нет.

Добавлено через 39 секунд
Советую почитать про структуры с самоадресацией для начала чтобы понять логику программы.
0
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
09.01.2014, 01:44  [ТС] 9
MrGluck, то есть получается что создается новая структура с теми же параметрами предыдущей структуры?
0
Форумчанин
Эксперт CЭксперт С++
8215 / 5045 / 1437
Регистрация: 29.11.2010
Сообщений: 13,453
09.01.2014, 01:45 10
что за "параметры предыдущей среды" ? Под этим можно что угодно понимать. Структура всех узлов одинакова, если вы хотите об этом спросить.
0
9 / 9 / 6
Регистрация: 12.07.2013
Сообщений: 57
09.01.2014, 01:48  [ТС] 11
MrGluck, Да да, именно это я хотел спросить.
А вот в таком примере:
Олимпиада - страна - вид спорта - спортсмен.

Тоже будет структура, с одним полем текста, правильно? И такое поле будет для всех узлов?
0
25 / 25 / 12
Регистрация: 04.01.2014
Сообщений: 91
09.01.2014, 02:26 12
moomot, Вот вам бинарное, и даже сбалансированное (AVL) дерево:

хедр:
C++
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
#ifndef AVL_TREE_H
#define AVL_TREE_H
 
#include <iostream>
#include <iomanip>
 
using namespace std;
 
struct node
{
    int key;
    int height;
    node *parent;
    node *left_child;
    node *right_child;
 
    node (int, node*); 
    node(int, int, node*, node*, node*); 
    ~node();
 
    void calc_height(); //рассчитывает высоту узла (исходя из условия что высота потомков уже рассчитана).
    int get_balance_factor(); //возвращает балланс-фактор для данного узла.
};
 
class AVL_tree {
private:
    node *root;
    int num_nodes; //кол-во узлов в дереве.
 
    node *GetMinChild(node *_node); //возвращает указатель на минимального потомка узла.
    void RecursPrintTree(node *_node);
    void DeleteSimpleNode(node*); //удаление узла, у которого не более одного дочернего узла.
    void ClearRecursion(node*); //вызывается деструктором.
 
    void Rotate(node*, bool); //поворот поддерева относительно его корня (в какую сторону - определяется параметром bool).
    void Balance(node*); //баллансировка узла.
 
public:
    AVL_tree();
    ~AVL_tree();
 
    void Insert_node (int);
    bool Delete_node (int); 
    node* SearchByKey (int);
    void Clear_tree();
 
    void Print_tree();
};
 
#endif
си-пи-пишник с мембер-функциями авл дерева:
C++
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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
#include "AVL_tree.h"
 
node::node (int _key, node *_parent) 
{
    key = _key;
    height = 1;
    parent = _parent;
    left_child = nullptr;
    right_child = nullptr;
}
 
node::~node()
{
}
 
void node::calc_height()
{
    if (left_child && right_child) {
        height = max(left_child->height, right_child->height) + 1;
    }
    else if (left_child) {
        height = left_child->height + 1;
    }
    else if (right_child) {
        height = right_child->height + 1;
    }
    else {
        height = 1;
    }
}
 
int node::get_balance_factor()
{
    int l_h = left_child ? left_child->height : 0;
    int r_h = right_child ? right_child->height : 0;
 
    return r_h - l_h;
}
 
 
AVL_tree::AVL_tree()
{
    root = new node(0, nullptr);
    num_nodes = 0;
}
 
AVL_tree::~AVL_tree()
{
    ClearRecursion(root);
}
 
void AVL_tree::Insert_node (int ins_key)
{
    if (!num_nodes) {
        root->key = ins_key;
        num_nodes++;
        return;
    }
        
    node *cur_node = root;
    while (true) {
        if (ins_key < cur_node->key) {
            if (cur_node->left_child) {
                cur_node = cur_node->left_child;
            }
            else {
                cur_node->left_child = new node(ins_key, cur_node); 
                break;
            }
        }
        else {
            if (cur_node->right_child) {
                cur_node = cur_node->right_child;
            }
            else {
                cur_node->right_child = new node(ins_key, cur_node);
                break;
            }
        }
    }
    num_nodes++;
 
    while (cur_node) { //баллансируем.
        cur_node->calc_height();
        Balance(cur_node);
        cur_node = cur_node->parent;
    }
}
 
bool AVL_tree::Delete_node(int del_key)  //дерево баллансируется в функции DeleteSimpleNode(...).
{
    node *del_node = SearchByKey(del_key);
 
    if (num_nodes && del_node) { //если такой узел присутствует в дереве.
        if (!del_node->left_child || !del_node->right_child) { //если у узла del_node не более одного дочерних узла.
            DeleteSimpleNode(del_node);
        }
        else {   //если у узла del_node два дочерних узла.
            node *successor_node = GetMinChild(del_node->right_child);
            del_node->key = successor_node->key;
 
            DeleteSimpleNode(successor_node);
        }
        num_nodes--;
        return true;
    }
    else {
        return false;
    }
 
} 
 
node* AVL_tree::SearchByKey(int seek_key)
{
    node *cur_node = root;
    while (cur_node && cur_node->key != seek_key) {
        if (seek_key < cur_node->key) {
            cur_node = cur_node->left_child;
        }
        else {
            cur_node = cur_node->right_child;
        }
    }
    return cur_node;
}
 
void AVL_tree::Clear_tree()
{
    ClearRecursion(root->left_child);
    ClearRecursion(root->right_child);
    num_nodes = 0;
    root->left_child = nullptr;
    root->right_child = nullptr;
    root->height = 1;
}
 
void AVL_tree::Print_tree()
{
    if (num_nodes) {
        RecursPrintTree(root);
    }
    else {
        cout <<"Дерево пусто.\n";
    }
}
 
void AVL_tree::RecursPrintTree(node *_node)
{
    node *cur_node = _node;
    cout <<cur_node->key <<"(" <<cur_node->height <<"): ";
    if (cur_node->left_child) {
        cout <<cur_node->left_child->key <<"(l) ";
    }
    else {
        cout <<"     ";
    }
    if (cur_node->right_child) {
        cout <<cur_node->right_child->key <<"(r) ";
    }
    cout <<'\n';
 
    if (cur_node->left_child) {
        RecursPrintTree(cur_node->left_child);
    }
    if (cur_node->right_child) {
        RecursPrintTree(cur_node->right_child);
    }
}
                                          
node* AVL_tree::GetMinChild(node *_node)
{
    node *cur_node = _node;
    
    while (cur_node->left_child) {
        cur_node = cur_node->left_child;
    }
 
    return cur_node;
}
 
void AVL_tree::DeleteSimpleNode(node *del_node) 
{
    if (!del_node->right_child) {  //если у узла del_node нет правого дочернего узла.
        if (del_node == root) {
            root = del_node->left_child;
            if (!root) {
                root = new node(0, nullptr);
            }
        }
        else if (del_node == del_node->parent->left_child) {
            del_node->parent->left_child = del_node->left_child;
        }
        else if (del_node == del_node->parent->right_child) {
            del_node->parent->right_child = del_node->left_child;
        }
 
        if (del_node->left_child) {
            del_node->left_child->parent = del_node->parent;
        }
    }
    else if (!del_node->left_child) {  //если у узла del_node нет левого дочернего узла.
        if (del_node == root) {
            root = del_node->right_child;
            if (!root) {
                root = new node(0, nullptr);
            }
        }
        else if (del_node == del_node->parent->left_child) {
            del_node->parent->left_child = del_node->right_child;
        }
        else if (del_node == del_node->parent->right_child) {
            del_node->parent->right_child = del_node->right_child;
        }
 
        if (del_node->right_child) {
            del_node->right_child->parent = del_node->parent;
        }
    }
    node *cur_node = del_node->parent;
    delete del_node;
 
    while (cur_node) {  //баллансируем.
        cur_node->calc_height();
        Balance(cur_node);
        cur_node = cur_node->parent;
    }
}
 
void AVL_tree::ClearRecursion(node *start_clear_node)
{
    node *cur_clear_node = start_clear_node;
    if (cur_clear_node) {
        ClearRecursion(cur_clear_node->left_child);
        ClearRecursion(cur_clear_node->right_child);
        delete cur_clear_node;
    }
}
 
void AVL_tree::Rotate(node *rotate_node, bool rl_flag)  //не доделана.
{
    if (rl_flag) { //поворачиваем вправо.
        node *l_ch = rotate_node->left_child;
        if (rotate_node->parent && rotate_node->parent->left_child == rotate_node) {
            rotate_node->parent->left_child = l_ch;
        }
        else if (rotate_node->parent && rotate_node->parent->right_child == rotate_node) {
            rotate_node->parent->right_child = l_ch;
        }
        node *save_right = l_ch->right_child;
        l_ch->right_child = rotate_node;
        rotate_node->left_child = save_right;
 
        l_ch->parent = rotate_node->parent;
        rotate_node->parent = l_ch;
        if (rotate_node->left_child) {
            rotate_node->left_child->parent = rotate_node;
        }
 
        rotate_node->calc_height();
        l_ch->calc_height();
 
        if (rotate_node == root) {
            root = l_ch;
        }
    }
    else { //поворачиваем влево.
        node *r_ch = rotate_node->right_child;
        if (rotate_node->parent && rotate_node->parent->left_child == rotate_node) {
            rotate_node->parent->left_child = r_ch;
        }
        else if (rotate_node->parent && rotate_node->parent->right_child == rotate_node) {
            rotate_node->parent->right_child = r_ch;
        }
        node *save_left = r_ch->left_child;
        r_ch->left_child = rotate_node;
        rotate_node->right_child = save_left;
 
        r_ch->parent = rotate_node->parent;
        rotate_node->parent = r_ch;
        if (rotate_node->right_child) {
            rotate_node->right_child->parent = rotate_node;
        }
        
        rotate_node->calc_height();
        r_ch->calc_height();
 
        if (rotate_node == root) {
            root = r_ch;
        }
    }
}
 
void AVL_tree::Balance(node *b_node)
{
    if (b_node->get_balance_factor() == -2) {
        if (b_node->left_child->get_balance_factor() < 0) {
            Rotate(b_node->left_child, true);
        }
        else if (b_node->left_child->get_balance_factor() > 0) {
            Rotate(b_node->left_child, false);
        }
        Rotate(b_node, true);
    }
    else if (b_node->get_balance_factor() == 2) {
        if (b_node->right_child->get_balance_factor() < 0) {
            Rotate(b_node->right_child, true);
        }
        else if (b_node->right_child->get_balance_factor() > 0) {
            Rotate(b_node->right_child, false);
        }
        Rotate(b_node, false);
    }
}
мейн:
C++
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
118
119
120
121
122
123
124
125
#include "AVL_tree.h"
 
#include <iostream>
#include <fstream>
#include <locale>
#include <string>
#include <iomanip>
#include <ctime>
 
using namespace std;
 
const int START_SIZE = 1000;
const int MAX_SIZE = 100000;
const int SIZE_STEP = 1000;
 
void Test_Tree();
void Get_Time(ofstream&);
 
int main()
{
    locale::global(locale("Russian"));
 
    ofstream results("D:\\AVL_functions.txt");
 
    string Command;
    cout <<"Список команд:\n"
         <<"\t\"Test_Tree\" - тестировать дерево;\n"
         <<"\t\"Get_Time\" - измерить время работы функций;\n"
         <<"Введите команду: ";
    cin >>Command;
 
    if (Command == "Test_Tree") {
        Test_Tree();
    }
    else if (Command == "Get_Time") {
        Get_Time(results);
    }
    else {
        cout <<"Неизвестная команда.\n";
    }
 
    return 0;
}
 
void Test_Tree()
{
    AVL_tree Tree;
    string Command;
    int key;
    bool success;
 
    while (true) {
        cout <<"Введите команду: ";
        cin >>Command;
 
        if (Command == "Insert_node") {
            cout <<"Введите ключ: ";
            cin >>key;
            Tree.Insert_node(key);
        }
        else if (Command == "Delete_node") {
            cout <<"Введите ключ: ";
            cin >>key;
            success = Tree.Delete_node(key);
            if (!success) {
                cout <<"Узла с таким ключом в дереве нет.\n";
            }
        }
        else if (Command == "Clear_tree") {
            Tree.Clear_tree();
        }
        else if (Command == "Print") {
            Tree.Print_tree();
        }
        else if (Command == "end_test") {
            break;
        }
        else {
            cout <<"Неизвестная команда\n";
        }
    }
}
 
void Get_Time(ofstream &res)
{
    AVL_tree Tree;
    double dur_insert, dur_delete, dur_search, dur_clear;
    int cur_size, i;
    clock_t start, finish;
 
    for (cur_size = START_SIZE; cur_size <= MAX_SIZE; cur_size += SIZE_STEP) {
        start = clock();
        for (i = 0;  i < cur_size; i++) {
            Tree.Insert_node(rand());
        }
        finish = clock();
        dur_insert = (double)(finish-start)/CLOCKS_PER_SEC;
 
        start = clock();
        for (i = 0; i < cur_size; i++) {
            Tree.Delete_node(rand());
        }
        finish = clock();
        dur_delete = (double)(finish-start)/CLOCKS_PER_SEC;
 
        Tree.Clear_tree();
        for (i = 0;  i < cur_size; i++) {
            Tree.Insert_node(rand());
        }
 
        start = clock();
        for (i = 0; i < cur_size; i++) {
            Tree.SearchByKey(rand());
        }
        finish = clock();
        dur_search = (double)(finish-start)/CLOCKS_PER_SEC;
 
        start = clock();
        Tree.Clear_tree();
        finish = clock();
        dur_clear = (double)(finish-start)/CLOCKS_PER_SEC;
 
        res <<left <<setw(15) <<cur_size <<setw(15) <<dur_insert <<setw(15) <<dur_delete <<setw(15) <<dur_search <<setw(15) <<dur_clear <<'\n';
    }
}
1
09.01.2014, 02:26
IT_Exp
Эксперт
87844 / 49110 / 22898
Регистрация: 17.06.2006
Сообщений: 92,604
09.01.2014, 02:26
Помогаю со студенческими работами здесь

деревья на С++
эта задачка на деревья.помогите пожалуйста...от этого зависит мой экзамен... В школе...

деревья
Почему не компилируется код вот тут проблема if (x&lt;(*Node)-&gt;l) Add(x,&amp;(*Node)-&gt;l); #include...

Б+ деревья
Здравствуйте. Собственно недавно совсем столкнулся с проблемой по реализации Б+ дерева... имею код...

деревья
всем доброго времени суток :) помогите разобраться с деревьями .... нужно создать клас,...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
12
Ответ Создать тему
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2024, CyberForum.ru