С Новым годом! Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.50/6: Рейтинг темы: голосов - 6, средняя оценка - 4.50
0 / 0 / 0
Регистрация: 07.04.2021
Сообщений: 24

LNK1120 и LNK2019 проверьте код

27.04.2021, 18:04. Показов 1126. Ответов 6
Метки c++ (Все метки)

Студворк — интернет-сервис помощи студентам
Почему выводится ошибка LNK1120 и LNK2019

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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <clocale>
using namespace std;
 
class TreeNode {
public:
    int value;
    TreeNode* right;
    TreeNode* left;
 
    TreeNode() {
        value = 0;
        right = left = NULL;
    }
};
class BST {
public:
    TreeNode* root;
    int height;
    double size;
 
    BST() { //Binary Search Tree(Бинарное Дерево Поиска)
        root = NULL;
    }
 
    //Функции, которые должно выполнять Бинарное Дерево Поиска 
    // 1. Поиск значения
    TreeNode* searchBST(int key, TreeNode* start) {
        //check if start is null
        if (start == NULL) {
            setlocale(LC_ALL, "Russian");
            cout << "Не найдено!" << endl;
            return NULL;
        }
        //check to see if you've found it (anchor value)
        else if (key == start->value) {
            setlocale(LC_ALL, "Russian");
            cout << "Полученное значение: " << endl;
            return start;
        }
        //if you havent found it, if the key is less than the value of the node you are at go left, it it's greater, go right
        else {
            if (key > start->value)
                searchBST(key, start->right);
            else
                searchBST(key, start->left);
        }
    }
 
    void Add(int avalue, TreeNode*& aTreeNode)
 
    {
 
        //Если ветки не существует
 
        if (!aTreeNode)
 
        { //создадим ее и зададим в нее данные
 
            aTreeNode = new TreeNode;
 
            aTreeNode->value = avalue;
 
            aTreeNode->left = 0;
 
            aTreeNode->right = 0;
 
            return;
 
        }
 
        else //Иначе сверим вносимое
 
            if (aTreeNode->value > avalue)
 
            { //Если оно меньше того, что в этой ветке - добавим влево
 
                Add(avalue, aTreeNode->left);
 
            }
 
            else
 
            { //Иначе в ветку справа
 
                Add(avalue, aTreeNode->right);
 
            };
 
    }
    // 2. Add new values to the tree
    void addNodeBST(int key) {
        // you can't use recursion for this
        TreeNode* slow, * fast;
        slow = fast = root;
        // want fast to fall off the tree
        // Step 1: Search for Key
        if (root == NULL) {
            root = new TreeNode;
            root->value = key;
            size++;
            return;
        }
        else {
            //use "fast" to go look for this 'key'
            // if "fast" falls off the tree, then this value does not exist
            //at this point, 'slow' to point to the parent of the new node
            //start by searching for this value
            //If you find it, don't add it. Just write a comment
            //If you don't find it. add it where you should have found it
            while (fast != NULL) {
                if (fast->value == key) {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дубликат" << endl; //This is when you don't want duplicates
                    return;
                }
                else if (key > fast->value) {
                    slow = fast;
                    fast = fast->right;
                }
                else {
                    slow = fast;
                    fast = fast->left;
                }
            } //fast should have fallen off the tree
            //slow happens to be at the node which will become the new parent
            TreeNode* temp = new TreeNode;
            temp->value = key;
 
            if (key > slow->value) {
                slow->right = temp;
                size++;
            }
            else {
                slow->left = temp;
                size++;
            }
        }
    }
 
    // Step 4. Ways to display the content of the tree
    // In order trasnversal: must go to every value and print them out
    //Left->current-> right
    // Left, center, and right
    // With our example it would be 10,12,13,15,17,18,23
    void inorder(TreeNode* start) {
        if (start == NULL) {
            return;
        }
        else {
            inorder(start->left);
            cout << start->value << " " << endl;
            inorder(start->right);
        }
    }
 
    //PreOrder Transveral:
    //Current Node->Left node->Right node
    //15 12 10 13 18 17 23
    void preorder(TreeNode* start) {
        if (start == NULL) {
            return;
        }
        else {
            cout << start->value << " " << endl;
            preorder(start->left);
            preorder(start->right);
        }
    }
 
    //Post Order:
    //Left->Right->Center
    //Prefixes are with Root
    // pre->Root first
    //Post->Root last
    void postorder(TreeNode* start) {
        if (start == NULL) {
        }
        else {
            postorder(start->left);
            postorder(start->right);
            cout << start->value << " " << endl;
        }
    }
 
    /*int minValRSubTree(TreeNode *start) {
        int value;
        TreeNode *temp = start;
        while (temp->left != NULL) {
            temp = temp->left;
        }
        return temp->value;
    } */
    int maxValLSubTree(TreeNode* start) {
        TreeNode* temp2 = start;
        while (temp2->right != NULL) {
            temp2 = temp2->right;
        }
        return temp2->value;
    }
    void placeBranch(TreeNode* branch)
    {
        //start everything at the root
        TreeNode* slow;
        TreeNode* fast;
        slow = fast = root;
        //if you pass the function a null pointer
        if (branch == NULL) {
            //  cout<<"Null Pointer, no nodes needed to be moved"<<endl;
            return;
        }
        else {
            //use fast to go look for the key
            //if fast falls off of the tree then this value does not exist
            //at that point we want slow to point to the parent of the new node
            while (fast != NULL) {
                if (branch->value > fast->value) {
                    slow = fast;
                    fast = fast->right;
                }
                else {
                    slow = fast;
                    fast = fast->left;
                }
            }
            //at this point fast should have fallen off of the tree
            //slow happens to be at the parent node
 
            //same thing as the add function, greater -> right  less -> left
            if (branch->value > slow->value) {
                slow->right = branch;
            }
            else {
                slow->left = branch;
            }
        }
 
    }
    //Code will print the following: 10 13 12 17 23 18 15
    // 3. Delete values from the tree
    void deleteNodeBST(int key, TreeNode* start) {
        //if empty
        if (root == NULL) {
            setlocale(LC_ALL, "Russian");
            cout << "Пустое дерево" << endl;
            return;
        }
        //everything else
        else {
            TreeNode* marked;
            TreeNode* grabL;
            TreeNode* grabR;
            TreeNode* helper;
 
            //make a helper pointer that starts at the beginning
            helper = start;
 
            //grab the address of the node you want to delete, the search function was mdoified to return an address
            marked = searchBST(key, root);
 
            //if you are looking for something that does not exist the break out
            if (marked == NULL) {
                setlocale(LC_ALL, "Russian");
                cout << "Значение не существует в дереве!" << endl;
                return;
            }
 
            //if what you're looking for exists then grab the addresses of its children so you don't demolish the whole structure
            grabL = marked->left;
            grabR = marked->right;
 
            //if root is marked make the node to the right of it root (my convention) and then place the left side where it should be
            //the delete the marked node
            if (marked == root) {
                root = root->right;
                placeBranch(grabL);
                delete marked;
                size -= 1;
                return;
            }
 
            //if your children aren't marked for death then traverse down the structure with tree until you get to the parent of a marked node
            while (helper->left != marked && helper->right != marked) {
                if (key > helper->value) {
                    helper = helper->right;
                }
                else if (key < helper->value) {
                    helper = helper->left;
                }
                //shouldnt get here. This means that helper didn't find the value or helper ended up on the marked node, or the other NULL failsafes didn't work
                else {
                    setlocale(LC_ALL, "Russian");
                    cout << "Хьюстон, у нас есть проблемы" << endl;
                }
            }
 
            //if your child is marked then null the connection, delete the marked node, and then place its children where they should be
            //Left then Right, I just did it in that order as a convention
            if (helper->left == marked) {
                helper->left = NULL;
                delete marked;
                size -= 1;
                placeBranch(grabL);
                placeBranch(grabR);
            }
            else if (helper->right == marked) {
                helper->right = NULL;
                delete marked;
                size -= 1;
                placeBranch(grabL);
                placeBranch(grabR);
            }
        }
    }
 
 
    //Stuff for the Exam 2:
    //---------------------------------------------------------
    //Question 8
    void deleteTree(TreeNode* node) {
        setlocale(LC_ALL, "Russian");
        if (node == NULL)
            return;
        deleteTree(node->left);
        deleteTree(node->right);
        cout << " Удаление узла: " << endl << node->value;
        deleteNodeBST(node->value, root);
        size = 0;
        cout << endl;
    }
 
    //Question 9
    bool isBalanced(TreeNode* start) {
        if (start == NULL) {
            setlocale(LC_ALL, "Russian");
            cout << "Дерево пусто в начале" << endl;
            return true;
        }
        else {            //height in general is root to leaf node
            int lHeight = 0;
            int rHeight = 0;
            TreeNode* hL = start;
            TreeNode* hR = start;
 
            while (hL != NULL) {
                hL = hL->left;
                lHeight++;
            }
            while (hR != NULL) {
                hR = hR->right;
                rHeight++;
            }
 
            if ((lHeight == rHeight) || (lHeight == rHeight + 1) || (lHeight + 1 == rHeight)) {
                return true;
            }
            else {
                return false;
            }
        }
    }
 
    //Question 10:
    int findNodeFound(TreeNode* root, int val) // Searching whether the given value is found in the BST
    {
        if (root == NULL)
            return 0;
        else if (root->value == val)
            return 1;
 
        else if (root->value > val)
            return findNodeFound(root->left, val);
        else
            return findNodeFound(root->right, val);
    }
 
    int firstCommonParent(TreeNode* root, int value1, int value2) // Finding FirstCommonParent of given values
    {
        int flag1 = 0, flag2 = 0;
        flag1 = findNodeFound(root, value1);
        flag2 = findNodeFound(root, value2);
        if (flag1 == 1 && flag2 == 1)
        {
            while (1)
            {
                if (root == NULL)
                    return 0;
                else if ((root->value > value1) && (root->value > value2))
                    root = root->left;
                else if ((root->value < value1) && (root->value < value2))
                    root = root->right;
                else
                    break;
            }
            return root->value;
        }
        else
        {
            setlocale(LC_ALL, "Russian");
            cout << " Значения не найдены в BST" << endl;
            return 0;
        }
    };
 
    //If they give you values like 1,2,3,4,5,6,7,8,9
    //Use self balancing trees:
    //AVL and Red Black Trees
    //They use rotation to fix this problem
    int main() {
        setlocale(LC_ALL, "Russian");
        BST myTree;
        int choice, value;
        TreeNode* Root = 0;
        int vel;
        cout << "Введите кол-во элементов для будущего дерева: ";
        cin >> vel;
        cout << endl;
        for (int i = 0; i < vel; i++)
 
        {
 
            Add(rand() % 100, Root);
 
        }
        while (1) {
            setlocale(LC_ALL, "Russian");
            cout << "Нажмите 1, чтобы добавить BST-> " << endl;
            cout << "Нажмите 2 для поиска BST-> " << endl;
            cout << "Нажмите 3, чтобы удалить-> " << endl;
            cout << "Нажмите 4, для симметричного обхода-> " << endl;
            cout << "Нажмите 5, для прямого обхода-> " << endl;
            cout << "Нажмите 6, для обратного обхода-> " << endl;
            cout << "Нажмите 7, чтобы удалить дерево-> " << endl;
            cout << "Нажмите 8, чтобы проверить, на сбаланированность дерева-> " << endl;
            cout << "Нажмите 9, для общего родителя двух узлов->" << endl;
            cin >> choice;
            switch (choice) {
                setlocale(LC_ALL, "Russian");
            case 1:
                cout << "Что добавить? " << endl;
                cin >> value;
                myTree.addNodeBST(value);
                break;
            case 2:
                cout << "Что вы ищете? " << endl;
                cin >> value;
                myTree.searchBST(value, myTree.root);
                break;
            case 3:
                int value;
                cout << "Какое значение вы хотели бы удалить? " << endl;
                cin >> value;
                myTree.deleteNodeBST(value, myTree.root);
                break;
            case 4:
                myTree.inorder(myTree.root);
                break;
            case 5:
                myTree.preorder(myTree.root);
                break;
            case 6:
                myTree.postorder(myTree.root);
                break;
            case 7:
                myTree.deleteTree(myTree.root);
                break;
            case 8:
                if (myTree.isBalanced(myTree.root) == 1) {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дерево сбалансированно " << endl;
                }
                else {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дерево несбалансированно " << endl;
                }
                setlocale(LC_ALL, "Russian");
                break;
            case 9:
                int value1 = 0;
                int value2 = 0;
                cout << "Вставьте два числа с одним и тем же родителем " << endl;
                cin >> value1;
                cin >> value2;
                int flag = myTree.firstCommonParent(myTree.root, value1, value2);
                if (flag != 0) {
                    setlocale(LC_ALL, "Russian");
                    cout << "Первым Общим родителем является " << flag << endl;
                }
                else {
                    setlocale(LC_ALL, "Russian");
                    cout << "Общий родитель не найден " << endl;
                }
                break;
            }
        }
    }
};
0
Лучшие ответы (1)
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
27.04.2021, 18:04
Ответы с готовыми решениями:

LNK2019 и LNK1120
Программа состоит из 3ех файлов: names.h #ifndef NAMES_H_ #define NAMES_H_ namespace SALES { const int QUARTERS = 4; struct...

LNK2019, LNK1120
#include &lt;windows.h&gt; int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int ...

LNK1120 .LNK2019
помогите пожалуйста . Заранее спасибо LNK1120 неразрешенных внешних элементов :1 LNK2019 ссылка на неразрешённый внещний символ...

6
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
12930 / 6798 / 1820
Регистрация: 18.10.2014
Сообщений: 17,208
27.04.2021, 18:36
Цитата Сообщение от LastDrgn Посмотреть сообщение
выводится ошибка LNK1120 и LNK2019
Почему в вопросе не приведена дословная копия текста ошибок???

Где в этой программе функция main?
1
0 / 0 / 0
Регистрация: 07.04.2021
Сообщений: 24
27.04.2021, 18:41  [ТС]
Цитата Сообщение от TheCalligrapher Посмотреть сообщение
Где в этой программе функция main?
А где она должна стоять?

Добавлено через 27 секунд
Цитата Сообщение от TheCalligrapher Посмотреть сообщение
Где в этой программе функция main?
Можете показать?
0
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
12930 / 6798 / 1820
Регистрация: 18.10.2014
Сообщений: 17,208
27.04.2021, 18:48
Цитата Сообщение от LastDrgn Посмотреть сообщение
А где она должна стоять?
Не понял. Кто должен стоять? Еще раз: где ваша main? Покажите мне ее пальцем?
1
0 / 0 / 0
Регистрация: 07.04.2021
Сообщений: 24
27.04.2021, 18:50  [ТС]
Цитата Сообщение от TheCalligrapher Посмотреть сообщение
Не понял. Кто должен стоять? Еще раз: где ваша main? Покажите мне ее пальцем?
413 строчка
0
Вездепух
Эксперт CЭксперт С++
 Аватар для TheCalligrapher
12930 / 6798 / 1820
Регистрация: 18.10.2014
Сообщений: 17,208
27.04.2021, 18:51
Цитата Сообщение от LastDrgn Посмотреть сообщение
Вот
Это не main, это BST::main.

Если вы хотели, чтобы это было вашей функцией main, то почему вы засунули ее внутрь BST?
1
Мозгоправ
 Аватар для L0M
1745 / 1039 / 468
Регистрация: 01.10.2018
Сообщений: 2,138
Записей в блоге: 2
27.04.2021, 19:10
Лучший ответ Сообщение было отмечено LastDrgn как решение

Решение

LastDrgn, кроме main() у вас там ещё ляпы были. Поправил. На работоспособность не проверял. Посмотрите предупреждение "Warning C28182 Dereferencing NULL pointer. 'slow' contains the same NULL value as 'fast' did."
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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <clocale>
using namespace std;
 
class TreeNode {
public:
    int value;
    TreeNode *right;
    TreeNode *left;
 
    TreeNode()
    {
        value = 0;
        right = left = NULL;
    }
};
class BST {
public:
    TreeNode *root;
    int height;
    double size;
 
    BST()
    { //Binary Search Tree(Бинарное Дерево Поиска)
        root = NULL;
        height = 0;
        size = 0.0;
    }
 
    //Функции, которые должно выполнять Бинарное Дерево Поиска 
    // 1. Поиск значения
    TreeNode *searchBST(int key, TreeNode *start)
    {
        TreeNode *retVal = NULL;
 
        //check if start is null
        if (start == NULL)
        {
            setlocale(LC_ALL, "Russian");
            cout << "Не найдено!" << endl;
        }
        //check to see if you've found it (anchor value)
        else if (key == start->value)
        {
            setlocale(LC_ALL, "Russian");
            cout << "Полученное значение: " << endl;
            retVal = start;
        }
        //if you havent found it, if the key is less than the value of the node you are at go left, it it's greater, go right
        else
        {
            if (key > start->value)
                retVal = searchBST(key, start->right);
            else
                retVal = searchBST(key, start->left);
        }
        return retVal;
    }
 
    void Add(int avalue, TreeNode *&aTreeNode)
 
    {
 
        //Если ветки не существует
 
        if (!aTreeNode)
 
        { //создадим ее и зададим в нее данные
 
            aTreeNode = new TreeNode;
 
            aTreeNode->value = avalue;
 
            aTreeNode->left = 0;
 
            aTreeNode->right = 0;
 
            return;
 
        }
 
        else //Иначе сверим вносимое
 
            if (aTreeNode->value > avalue)
 
            { //Если оно меньше того, что в этой ветке - добавим влево
 
                Add(avalue, aTreeNode->left);
 
            }
 
            else
 
            { //Иначе в ветку справа
 
                Add(avalue, aTreeNode->right);
 
            };
 
    }
    // 2. Add new values to the tree
    void addNodeBST(int key)
    {
        // you can't use recursion for this
        TreeNode *slow, *fast;
        slow = fast = root;
        // want fast to fall off the tree
        // Step 1: Search for Key
        if (root == NULL)
        {
            root = new TreeNode;
            root->value = key;
            size++;
            return;
        }
        else
        {
            //use "fast" to go look for this 'key'
            // if "fast" falls off the tree, then this value does not exist
            //at this point, 'slow' to point to the parent of the new node
            //start by searching for this value
            //If you find it, don't add it. Just write a comment
            //If you don't find it. add it where you should have found it
            while (fast != NULL)
            {
                if (fast->value == key)
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дубликат" << endl; //This is when you don't want duplicates
                    return;
                }
                else if (key > fast->value)
                {
                    slow = fast;
                    fast = fast->right;
                }
                else
                {
                    slow = fast;
                    fast = fast->left;
                }
            } //fast should have fallen off the tree
            //slow happens to be at the node which will become the new parent
            TreeNode *temp = new TreeNode;
            temp->value = key;
 
            if (key > slow->value)
            {
                slow->right = temp;
                size++;
            }
            else
            {
                slow->left = temp;
                size++;
            }
        }
    }
 
    // Step 4. Ways to display the content of the tree
    // In order trasnversal: must go to every value and print them out
    //Left->current-> right
    // Left, center, and right
    // With our example it would be 10,12,13,15,17,18,23
    void inorder(TreeNode *start)
    {
        if (start == NULL)
        {
            return;
        }
        else
        {
            inorder(start->left);
            cout << start->value << " " << endl;
            inorder(start->right);
        }
    }
 
    //PreOrder Transveral:
    //Current Node->Left node->Right node
    //15 12 10 13 18 17 23
    void preorder(TreeNode *start)
    {
        if (start == NULL)
        {
            return;
        }
        else
        {
            cout << start->value << " " << endl;
            preorder(start->left);
            preorder(start->right);
        }
    }
 
    //Post Order:
    //Left->Right->Center
    //Prefixes are with Root
    // pre->Root first
    //Post->Root last
    void postorder(TreeNode *start)
    {
        if (start == NULL)
        {
        }
        else
        {
            postorder(start->left);
            postorder(start->right);
            cout << start->value << " " << endl;
        }
    }
 
    /*int minValRSubTree(TreeNode *start) {
        int value;
        TreeNode *temp = start;
        while (temp->left != NULL) {
            temp = temp->left;
        }
        return temp->value;
    } */
    int maxValLSubTree(TreeNode *start)
    {
        TreeNode *temp2 = start;
        while (temp2->right != NULL)
        {
            temp2 = temp2->right;
        }
        return temp2->value;
    }
    void placeBranch(TreeNode *branch)
    {
        //start everything at the root
        TreeNode *slow;
        TreeNode *fast;
        slow = fast = root;
        //if you pass the function a null pointer
        if (branch == NULL)
        {
            //  cout<<"Null Pointer, no nodes needed to be moved"<<endl;
            return;
        }
        else
        {
            //use fast to go look for the key
            //if fast falls off of the tree then this value does not exist
            //at that point we want slow to point to the parent of the new node
            while (fast != NULL)
            {
                if (branch->value > fast->value)
                {
                    slow = fast;
                    fast = fast->right;
                }
                else
                {
                    slow = fast;
                    fast = fast->left;
                }
            }
            //at this point fast should have fallen off of the tree
            //slow happens to be at the parent node
 
            //same thing as the add function, greater -> right  less -> left
            if (branch->value > slow->value)
            {
                slow->right = branch;
            }
            else
            {
                slow->left = branch;
            }
        }
 
    }
    //Code will print the following: 10 13 12 17 23 18 15
    // 3. Delete values from the tree
    void deleteNodeBST(int key, TreeNode *start)
    {
        //if empty
        if (root == NULL)
        {
            setlocale(LC_ALL, "Russian");
            cout << "Пустое дерево" << endl;
            return;
        }
        //everything else
        else
        {
            TreeNode *marked;
            TreeNode *grabL;
            TreeNode *grabR;
            TreeNode *helper;
 
            //make a helper pointer that starts at the beginning
            helper = start;
 
            //grab the address of the node you want to delete, the search function was mdoified to return an address
            marked = searchBST(key, root);
 
            //if you are looking for something that does not exist the break out
            if (marked == NULL)
            {
                setlocale(LC_ALL, "Russian");
                cout << "Значение не существует в дереве!" << endl;
                return;
            }
 
            //if what you're looking for exists then grab the addresses of its children so you don't demolish the whole structure
            grabL = marked->left;
            grabR = marked->right;
 
            //if root is marked make the node to the right of it root (my convention) and then place the left side where it should be
            //the delete the marked node
            if (marked == root)
            {
                root = root->right;
                placeBranch(grabL);
                delete marked;
                size -= 1;
                return;
            }
 
            //if your children aren't marked for death then traverse down the structure with tree until you get to the parent of a marked node
            while (helper->left != marked && helper->right != marked)
            {
                if (key > helper->value)
                {
                    helper = helper->right;
                }
                else if (key < helper->value)
                {
                    helper = helper->left;
                }
                //shouldnt get here. This means that helper didn't find the value or helper ended up on the marked node, or the other NULL failsafes didn't work
                else
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Хьюстон, у нас есть проблемы" << endl;
                }
            }
 
            //if your child is marked then null the connection, delete the marked node, and then place its children where they should be
            //Left then Right, I just did it in that order as a convention
            if (helper->left == marked)
            {
                helper->left = NULL;
                delete marked;
                size -= 1;
                placeBranch(grabL);
                placeBranch(grabR);
            }
            else if (helper->right == marked)
            {
                helper->right = NULL;
                delete marked;
                size -= 1;
                placeBranch(grabL);
                placeBranch(grabR);
            }
        }
    }
 
 
    //Stuff for the Exam 2:
    //---------------------------------------------------------
    //Question 8
    void deleteTree(TreeNode *node)
    {
        setlocale(LC_ALL, "Russian");
        if (node == NULL)
            return;
        deleteTree(node->left);
        deleteTree(node->right);
        cout << " Удаление узла: " << endl << node->value;
        deleteNodeBST(node->value, root);
        size = 0;
        cout << endl;
    }
 
    //Question 9
    bool isBalanced(TreeNode *start)
    {
        if (start == NULL)
        {
            setlocale(LC_ALL, "Russian");
            cout << "Дерево пусто в начале" << endl;
            return true;
        }
        else
        {            //height in general is root to leaf node
            int lHeight = 0;
            int rHeight = 0;
            TreeNode *hL = start;
            TreeNode *hR = start;
 
            while (hL != NULL)
            {
                hL = hL->left;
                lHeight++;
            }
            while (hR != NULL)
            {
                hR = hR->right;
                rHeight++;
            }
 
            if ((lHeight == rHeight) || (lHeight == rHeight + 1) || (lHeight + 1 == rHeight))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
 
    //Question 10:
    int findNodeFound(TreeNode *rootNode, int val) // Searching whether the given value is found in the BST
    {
        if (rootNode == NULL)
            return 0;
        else if (rootNode->value == val)
            return 1;
 
        else if (rootNode->value > val)
            return findNodeFound(rootNode->left, val);
        else
            return findNodeFound(rootNode->right, val);
    }
 
    int firstCommonParent(TreeNode *rootNode, int value1, int value2) // Finding FirstCommonParent of given values
    {
        int flag1 = 0, flag2 = 0;
        flag1 = findNodeFound(rootNode, value1);
        flag2 = findNodeFound(rootNode, value2);
        if (flag1 == 1 && flag2 == 1)
        {
            while (1)
            {
                if (rootNode == NULL)
                    return 0;
                else if ((rootNode->value > value1) && (rootNode->value > value2))
                    rootNode = rootNode->left;
                else if ((rootNode->value < value1) && (rootNode->value < value2))
                    rootNode = rootNode->right;
                else
                    break;
            }
            return rootNode->value;
        }
        else
        {
            setlocale(LC_ALL, "Russian");
            cout << " Значения не найдены в BST" << endl;
            return 0;
        }
    }
};
 
//If they give you values like 1,2,3,4,5,6,7,8,9
//Use self balancing trees:
//AVL and Red Black Trees
//They use rotation to fix this problem
int main()
{
    setlocale(LC_ALL, "Russian");
    BST myTree;
    int choice, value;
    TreeNode *Root = 0;
    int vel;
    cout << "Введите кол-во элементов для будущего дерева: ";
    cin >> vel;
    cout << endl;
    for (int i = 0; i < vel; i++)
 
    {
 
        myTree.Add(rand() % 100, Root);
 
    }
    while (1)
    {
        setlocale(LC_ALL, "Russian");
        cout << "Нажмите 1, чтобы добавить BST-> " << endl;
        cout << "Нажмите 2 для поиска BST-> " << endl;
        cout << "Нажмите 3, чтобы удалить-> " << endl;
        cout << "Нажмите 4, для симметричного обхода-> " << endl;
        cout << "Нажмите 5, для прямого обхода-> " << endl;
        cout << "Нажмите 6, для обратного обхода-> " << endl;
        cout << "Нажмите 7, чтобы удалить дерево-> " << endl;
        cout << "Нажмите 8, чтобы проверить, на сбаланированность дерева-> " << endl;
        cout << "Нажмите 9, для общего родителя двух узлов->" << endl;
        cin >> choice;
        switch (choice)
        {
            case 1:
                cout << "Что добавить? " << endl;
                cin >> value;
                myTree.addNodeBST(value);
                break;
            case 2:
                cout << "Что вы ищете? " << endl;
                cin >> value;
                myTree.searchBST(value, myTree.root);
                break;
            case 3:
                int value;
                cout << "Какое значение вы хотели бы удалить? " << endl;
                cin >> value;
                myTree.deleteNodeBST(value, myTree.root);
                break;
            case 4:
                myTree.inorder(myTree.root);
                break;
            case 5:
                myTree.preorder(myTree.root);
                break;
            case 6:
                myTree.postorder(myTree.root);
                break;
            case 7:
                myTree.deleteTree(myTree.root);
                break;
            case 8:
                if (myTree.isBalanced(myTree.root) == 1)
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дерево сбалансированно " << endl;
                }
                else
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Дерево несбалансированно " << endl;
                }
                setlocale(LC_ALL, "Russian");
                break;
            case 9:
            {
                int value1 = 0;
                int value2 = 0;
                cout << "Вставьте два числа с одним и тем же родителем " << endl;
                cin >> value1;
                cin >> value2;
                int flag = myTree.firstCommonParent(myTree.root, value1, value2);
                if (flag != 0)
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Первым Общим родителем является " << flag << endl;
                }
                else
                {
                    setlocale(LC_ALL, "Russian");
                    cout << "Общий родитель не найден " << endl;
                }
                break;
            }
            default:
                cout << "Неверный выбор. Попробуйте ещё раз...";
        }
    }
}
1
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.04.2021, 19:10
Помогаю со студенческими работами здесь

LNK2019 and LNK1120
Помогите пофиксить 2 ошибки. Не могу понять что от меня требуется. Вот код программы: // det.cpp: определяет точку входа для консольного...

LNK1120 и LNK2019
1&gt;------ Сборка начата: проект: Win32Project3, Конфигурация: Debug Win32 ------ 1&gt;stdAfx.cpp 1&gt;MSVCRTD.lib(exe_main.obj) : error...

Ошибка LNK2019, LNK1120
Помогите решить проблему #include &quot;stdafx.h&quot; #include &lt;iostream&gt; #include &lt;ctime&gt; #include &lt;windows.h&gt; #include...

Ошибка LNK2019-LNK1120
#include &quot;pch.h&quot; #include &lt;iostream&gt; using namespace std; class phone { public: int date; //дата int code; //код города ...

Error LNK2019 и LNK1120
Форумчане, помогите кто чем может. изучать язык только начал, поэтому куча вопросов и ошибок, а найденные ответы не сильно помогают, и...


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

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Новые блоги и статьи
Почему дизайн решает?
Neotwalker 09.01.2026
В современном мире, где конкуренция за внимание потребителя достигла пика, дизайн становится мощным инструментом для успеха бренда. Это не просто красивый внешний вид продукта или сайта — это. . .
Модель микоризы: классовый агентный подход 3
anaschu 06.01.2026
aa0a7f55b50dd51c5ec569d2d10c54f6/ O1rJuneU_ls https:/ / vkvideo. ru/ video-115721503_456239114
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR
ФедосеевПавел 06.01.2026
Owen Logic: О недопустимости использования связки «аналоговый ПИД» + RegKZR ВВЕДЕНИЕ Введу сокращения: аналоговый ПИД — ПИД регулятор с управляющим выходом в виде числа в диапазоне от 0% до. . .
Модель микоризы: классовый агентный подход 2
anaschu 06.01.2026
репозиторий https:/ / github. com/ shumilovas/ fungi ветка по-частям. коммит Create переделка под биомассу. txt вход sc, но sm считается внутри мицелия. кстати, обьем тоже должен там считаться. . . .
Расчёт токов в цепи постоянного тока
igorrr37 05.01.2026
/ * Дана цепь постоянного тока с сопротивлениями и напряжениями. Надо найти токи в ветвях. Программа составляет систему уравнений по 1 и 2 законам Кирхгофа и решает её. Последовательность действий:. . .
Новый CodeBlocs. Версия 25.03
palva 04.01.2026
Оказывается, недавно вышла новая версия CodeBlocks за номером 25. 03. Когда-то давно я возился с только что вышедшей тогда версией 20. 03. С тех пор я давно снёс всё с компьютера и забыл. Теперь. . .
Модель микоризы: классовый агентный подход
anaschu 02.01.2026
Раньше это было два гриба и бактерия. Теперь три гриба, растение. И на уровне агентов добавится между грибами или бактериями взаимодействий. До того я пробовал подход через многомерные массивы,. . .
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост.
Programma_Boinc 28.12.2025
Советы по крайней бережливости. Внимание, это ОЧЕНЬ длинный пост. Налог на собак: https:/ / **********/ gallery/ V06K53e Финансовый отчет в Excel: https:/ / **********/ gallery/ bKBkQFf Пост отсюда. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru