Форум программистов, компьютерный форум, киберфорум
С++ для начинающих
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
Рейтинг 4.86/7: Рейтинг темы: голосов - 7, средняя оценка - 4.86
 Аватар для stdin
129 / 81 / 49
Регистрация: 10.01.2020
Сообщений: 293

Обход бинарного дерева в ширину

19.05.2021, 15:18. Показов 1669. Ответов 12
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Я сделал функцию получения следующего узла от заданного узла бинарного дерева(с итератором) согласно обходу в ширину.
Возможно эту функцию можно сделать короче, оптимизированнее и надежнее. В интернетах(включая буржуйских) ничего похожего не нашел.
Так что может у кого-нибуть будут идеи? Сама функция работает.
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
bool is_end(simple_binary_tree_node* otherpNode)
        {
            simple_binary_tree_node* tempNode = otherpNode;
            while (!tempNode->pParent->m_isNil)
            {
                if (tempNode == tempNode->pParent->pLeft)
                {
                    return false;
                }
                tempNode = tempNode->pParent;
            }
            return true;
        }
simple_binary_tree_node* next_node(simple_binary_tree_node* currentNode)
        {
            if (currentNode->pRight && currentNode->pRight->m_isNil && this->is_end(currentNode))
            {
                simple_binary_tree_node* temp = currentNode;
                while (!temp->pParent->m_isNil)
                {
                    temp = temp->pParent;
                }
                return currentNode->pRight;
            }
            else
            {
                std::vector<bool> node_pos;
                simple_binary_tree_node* temp = currentNode;
                while (!temp->pParent->m_isNil)
                {
                    node_pos.insert(node_pos.begin(), (temp == temp->pParent->pRight));
                    temp = temp->pParent;
                }
                simple_binary_tree_node* temp_ = temp;
 
                bool flag = true;
                while (flag)
                {
                    int count = 0;
                    for (size_t i = 0; i < node_pos.size(); i++)
                    {
                        if (!node_pos[i])
                        {
                            count++;
                        }
                    }
                    if (!count)
                    {
                        std::vector<bool> newPos(node_pos.size() + 1, 0);
                        node_pos = newPos;
                    }
                    else
                    {
                        for (auto i = 0; i < node_pos.size(); i++)
                        {
                            count = 0;
                            for (auto j = (i + 1); j < node_pos.size(); j++)
                            {
                                if (!node_pos[j])
                                {
                                    count++;
                                }
                            }
                            if (!count)
                            {
                                if (!node_pos[i])
                                {
                                    for (auto k = i; k < node_pos.size(); k++)
                                    {
                                        node_pos[k] = !node_pos[k];
                                    }
                                }
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    flag = false;
                    for (size_t i = 0; i < node_pos.size(); i++)
                    {
                        if (node_pos[i])
                        {
                            if (temp && temp->pRight && temp->pRight->m_isNil)
                            {
                                flag = true;
                                temp = temp_;
                                break;
                            }
                            else
                            {
                                temp = temp->pRight;
                            }
                        }
                        else
                        {
                            if (temp && temp->pLeft && temp->pLeft->m_isNil)
                            {
                                flag = true;
                                temp = temp_;
                                break;
                            }
                            else
                            {
                                temp = temp->pLeft;
                            }
                        }
                    }
                    return temp;
                }
            }
        }
Коротко о функции, условно сделал путь к определенному узлу в виде std::vector<bool>, где 0 - левый узел, 1 - правый узел. Таким образом при проходке по дереву можно дойти до определенного элемента.
Также придумал своеобразную арифметику, помогающую получать вектор с путем к следующему элементу(согласно расположения в полностью сбалансированном дереве).
И далее проверка на то, есть ли узел с таким путем в дереве.
0
IT_Exp
Эксперт
34794 / 4073 / 2104
Регистрация: 17.06.2006
Сообщений: 32,602
Блог
19.05.2021, 15:18
Ответы с готовыми решениями:

Обход дерева в ширину
имеется такой кусок программы. требуется обойти дерево в ширину. библиотека #include &lt;queue&gt; подключена void...

Обход дерева в ширину
Кто нибудь может скинуть мне программу обхода дерева в ширину?

Обход дерева в ширину
Доброго времени суток. Нужно обойти бинарное дерево в ширину: struct TreePart { string data; TreePart* left = NULL; TreePart*...

12
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
19.05.2021, 20:55
Цитата Сообщение от stdin Посмотреть сообщение
Так что может у кого-нибуть будут идеи?
Покажи весь код
0
 Аватар для stdin
129 / 81 / 49
Регистрация: 10.01.2020
Сообщений: 293
20.05.2021, 10:27  [ТС]
oleg-m1973, Весь код:

Кликните здесь для просмотра всего текста
simple_binary_tree.h
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
#pragma once
#include "simple_binary_tree_node.h"
#include <vector>
 
template <typename KeyType, typename MappedType>
class simple_binary_tree
{
    using ValueType               = std::pair<KeyType, MappedType>;
    //using simple_binary_tree      = simple_binary_tree<KeyType, MappedType>;
    using simple_binary_tree_node = simple_binary_tree_node<KeyType, MappedType>;
 
 
    template <typename ItType>
    class basic_iterator
    {
        template <typename OtherItType>
        friend class basic_iterator;
        friend class simple_binary_tree;
 
    public:
        ValueType& operator*()
        {
            return this->m_pCurrentNode->m_Value;
        }
 
        ValueType* operator ->()
        {
            return &this->m_pCurrentNode->m_Value;
        }
 
        bool empty()
        {
            return !this->m_pCurrentNode;
        }
 
        ItType operator +(int otherStep) const
        {
            ItType tempIt = self();
            if (otherStep < 0)
            {
                return tempIt - (otherStep * (-1));
            }
            else
            {
                for (size_t i = 0; i < otherStep; i++)
                {
                    tempIt++;
                }
                return tempIt;
            }
        }
 
        ItType operator - (int otherStep) const
        {
            ItType tempIt = self();
            if (otherStep < 0)
            {
                return tempIt + (otherStep * (-1));
            }
            else
            {
                for (size_t i = 0; i < otherStep; i++)
                {
                    tempIt--;
                }
                return tempIt;
            }
        }
 
        basic_iterator& operator += (int otherStep)
        {
            *this = *this + otherStep;
            return *this;
        }
 
        basic_iterator& operator -= (int otherStep)
        {
            *this = *this - otherStep;
            return *this;
        }
 
        friend bool operator == (const ItType& leftIterator, const ItType& rightIterator)
        {
            return (leftIterator.m_pCurrentNode == rightIterator.m_pCurrentNode);
        }
 
        friend bool operator != (const ItType& leftIterator, const ItType& rightIterator)
        {
            return (leftIterator.m_pCurrentNode != rightIterator.m_pCurrentNode);
        }
 
 
    protected:
 
        bool is_end(simple_binary_tree_node* otherpNode)
        {
            simple_binary_tree_node* tempNode = otherpNode;
            while (!tempNode->pParent->m_isNil)
            {
                if (tempNode == tempNode->pParent->pLeft)
                {
                    return false;
                }
                tempNode = tempNode->pParent;
            }
            return true;
        }
 
        bool is_begin(simple_binary_tree_node* otherpNode)
        {
            simple_binary_tree_node* tempNode = otherpNode;
            while (!tempNode->pParent->m_isNil)
            {
                if (tempNode == tempNode->pParent->pRight)
                {
                    return false;
                }
                tempNode = tempNode->pParent;
            }
            return true;
        }
 
        ItType& self()
        {
            return static_cast<ItType&>(*this);
        }
 
        const ItType& self() const
        {
            return static_cast<const ItType&>(*this);
        }
 
        basic_iterator()
        {
            this->m_pCurrentNode = nullptr;
        }
 
        basic_iterator(simple_binary_tree_node* otherpValue)
        {
            this->m_pCurrentNode = otherpValue;
        }
 
        template <typename OtherItType>
        basic_iterator(const basic_iterator<OtherItType>& otherBase)
        {
            this->m_pCurrentNode = otherBase.m_pCurrentNode;
        }
 
        simple_binary_tree_node* m_pCurrentNode;
    };
 
public:
 
    class in_order_iterator : public basic_iterator<in_order_iterator>
    {
        friend class simple_binary_tree;
    private:
 
        in_order_iterator(simple_binary_tree_node* otherpNode) : basic_iterator<in_order_iterator>(otherpNode)
        {
        }
 
    public:
 
        in_order_iterator() : basic_iterator<in_order_iterator>()
        {
        }
 
        template <typename OtherItType>
        in_order_iterator(const basic_iterator<OtherItType>& otherBase) : basic_iterator<in_order_iterator>(otherBase)
        {
        }
 
        in_order_iterator& operator ++()
        {
            if (this->m_pCurrentNode->pRight && !this->m_pCurrentNode->pRight->m_isNil)
            {
                this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                while (!this->m_pCurrentNode->pLeft->m_isNil)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pLeft;
                }
            }
            else
            {
                if (this->m_pCurrentNode->pRight && this->m_pCurrentNode->pRight->m_isNil && this->is_end(this->m_pCurrentNode))
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
                else
                {
                    while (this->m_pCurrentNode->pParent->pRight == this->m_pCurrentNode)
                    {
                        this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                    }
                    this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                }
            }
            return *this;
        }
 
        in_order_iterator operator ++(int)
        {
            in_order_iterator temp(*this);
            ++(*this);
            return temp;
        }
 
        in_order_iterator& operator --()
        {
            if (this->m_pCurrentNode->pLeft && !this->m_pCurrentNode->pLeft->m_isNil)
            {
                this->m_pCurrentNode = this->m_pCurrentNode->pLeft;
                while (!this->m_pCurrentNode->pRight->m_isNil)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
            }
            else
            {
                if (this->m_pCurrentNode->pLeft && this->m_pCurrentNode->pLeft->m_isNil && this->is_begin(this->m_pCurrentNode))
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
                while (this->m_pCurrentNode->pParent->pLeft == this->m_pCurrentNode)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                } 
                this->m_pCurrentNode = this->m_pCurrentNode->pParent;
            }
            return *this;
        }
 
        in_order_iterator operator --(int)
        {
            in_order_iterator temp(*this);
            --(*this);
            return temp;
        }
 
    private:
    };
    class in_order_reverse_iterator : public basic_iterator<in_order_reverse_iterator>
    {
        friend class simple_binary_tree;
    private:
 
        in_order_reverse_iterator(simple_binary_tree_node* otherpNode) : basic_iterator<in_order_reverse_iterator>(otherpNode)
        {
        }
 
    public:
        in_order_reverse_iterator() : basic_iterator<in_order_reverse_iterator>()
        {
        }
 
        template <typename OtherItType>
        in_order_reverse_iterator(const basic_iterator<OtherItType>& otherBase) : basic_iterator<in_order_reverse_iterator>(otherBase)
        {
        }
 
        in_order_reverse_iterator& operator ++()
        {
            if (this->m_pCurrentNode->pLeft && !this->m_pCurrentNode->pLeft->m_isNil)
            {
                this->m_pCurrentNode = this->m_pCurrentNode->pLeft;
                while (!this->m_pCurrentNode->pRight->m_isNil)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
            }
            else
            {
                if (this->m_pCurrentNode->pLeft && this->m_pCurrentNode->pLeft->m_isNil && this->is_begin(this->m_pCurrentNode))
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
                while (this->m_pCurrentNode->pParent->pLeft == this->m_pCurrentNode)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                }
                this->m_pCurrentNode = this->m_pCurrentNode->pParent;
            }
            return *this;
        }
 
        in_order_reverse_iterator operator ++(int)
        {
            in_order_reverse_iterator temp(*this);
            ++(*this);
            return temp;
        }
 
        in_order_reverse_iterator& operator --()
        {
            if (this->m_pCurrentNode->pRight && !this->m_pCurrentNode->pRight->m_isNil)
            {
                this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                while (!this->m_pCurrentNode->pLeft->m_isNil)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pLeft;
                }
            }
            else
            {
                if (this->m_pCurrentNode->pRight && this->m_pCurrentNode->pRight->m_isNil && this->is_end(this->m_pCurrentNode))
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
                else
                {
                    while (this->m_pCurrentNode->pParent->pRight == this->m_pCurrentNode)
                    {
                        this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                    }
                    this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                }
            }
            return *this;
        }
 
        in_order_reverse_iterator operator --(int)
        {
            in_order_reverse_iterator temp(*this);
            --(*this);
            return temp;
        }
 
    private:
    };
    
    class in_wigth_iterator : public basic_iterator<in_wigth_iterator>
    {
        friend class simple_binary_tree;
    private:
 
        simple_binary_tree_node* next_node(simple_binary_tree_node* currentNode)
        {
            if (currentNode->pRight && currentNode->pRight->m_isNil && this->is_end(currentNode))
            {
                simple_binary_tree_node* temp = currentNode;
                while (!temp->pParent->m_isNil)
                {
                    temp = temp->pParent;
                }
                return currentNode->pRight;
            }
            else
            {
                std::vector<bool> node_pos;
                simple_binary_tree_node* temp = currentNode;
                while (!temp->pParent->m_isNil)
                {
                    node_pos.insert(node_pos.begin(), (temp == temp->pParent->pRight));
                    temp = temp->pParent;
                }
                simple_binary_tree_node* temp_ = temp;
 
                bool flag = true;
                while (flag)
                {
                    int count = 0;
                    for (size_t i = 0; i < node_pos.size(); i++)
                    {
                        if (!node_pos[i])
                        {
                            count++;
                        }
                    }
                    if (!count)
                    {
                        std::vector<bool> newPos(node_pos.size() + 1, 0);
                        node_pos = newPos;
                    }
                    else
                    {
                        for (auto i = 0; i < node_pos.size(); i++)
                        {
                            count = 0;
                            for (auto j = (i + 1); j < node_pos.size(); j++)
                            {
                                if (!node_pos[j])
                                {
                                    count++;
                                }
                            }
                            if (!count)
                            {
                                if (!node_pos[i])
                                {
                                    for (auto k = i; k < node_pos.size(); k++)
                                    {
                                        node_pos[k] = !node_pos[k];
                                    }
                                }
                                break;
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }
                    flag = false;
                    for (size_t i = 0; i < node_pos.size(); i++)
                    {
                        if (node_pos[i])
                        {
                            if (temp && temp->pRight && temp->pRight->m_isNil)
                            {
                                flag = true;
                                temp = temp_;
                                break;
                            }
                            else
                            {
                                temp = temp->pRight;
                            }
                        }
                        else
                        {
                            if (temp && temp->pLeft && temp->pLeft->m_isNil)
                            {
                                flag = true;
                                temp = temp_;
                                break;
                            }
                            else
                            {
                                temp = temp->pLeft;
                            }
                        }
                    }
                    return temp;
                }
            }
        }
 
        in_wigth_iterator(simple_binary_tree_node* otherpNode) : basic_iterator<in_wigth_iterator>(otherpNode)
        {
        }
 
    public:
 
        in_wigth_iterator() : basic_iterator<in_wigth_iterator>()
        {
        }
 
        template <typename OtherItType>
        in_wigth_iterator(const basic_iterator<OtherItType>& otherBase) : basic_iterator<in_wigth_iterator>(otherBase)
        {
        }
 
        in_wigth_iterator& operator ++()
        {
            this->m_pCurrentNode = next_node(this->m_pCurrentNode);
            return *this;
        }
 
        in_wigth_iterator operator ++(int)
        {
            in_wigth_iterator temp(*this);
            ++(*this);
            return temp;
        }
 
        in_wigth_iterator& operator --()
        {
            if (this->m_pCurrentNode->pLeft && !this->m_pCurrentNode->pLeft->m_isNil)
            {
                this->m_pCurrentNode = this->m_pCurrentNode->pLeft;
                while (!this->m_pCurrentNode->pRight->m_isNil)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
            }
            else
            {
                if (this->m_pCurrentNode->pLeft && this->m_pCurrentNode->pLeft->m_isNil && this->is_begin(this->m_pCurrentNode))
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pRight;
                }
                while (this->m_pCurrentNode->pParent->pLeft == this->m_pCurrentNode)
                {
                    this->m_pCurrentNode = this->m_pCurrentNode->pParent;
                }
                this->m_pCurrentNode = this->m_pCurrentNode->pParent;
            }
            return *this;
        }
 
        in_wigth_iterator operator --(int)
        {
            in_wigth_iterator temp(*this);
            --(*this);
            return temp;
        }
 
    private:
    };
 
    simple_binary_tree();
 
    ~simple_binary_tree();
 
    std::pair<in_order_iterator, bool> insert(const ValueType& otherValue)
    {
        return this->emplace(otherValue);
    }
 
    std::pair<in_order_iterator, bool> insert(ValueType&& otherValue)
    {
        return this->emplace(std::move(otherValue));
    }
    
    template< class InputIt >
    void insert(const InputIt& otherFirstIterator, const InputIt& otherLastIterator)
    {
        auto tempIt = otherFirstIterator;
        while (tempIt != otherLastIterator)
        {
            this->insert(*tempIt);
            tempIt++;
        }
    }
 
    void insert(std::initializer_list<ValueType> otherIList)
    {
        this->insert(otherIList.begin(), otherIList.end());
    }
 
    template< class... Args >
    std::pair<in_order_iterator, bool> emplace(Args&&... args)
    {
        simple_binary_tree_node* newNode = this->m_pRoot;
        for (const auto& value : { args... })
        {
            newNode = simple_binary_tree_node::get_allocated_new_node(value);
            simple_binary_tree_node* currentNode = this->m_pRoot->pRight;
 
            while (!currentNode->m_isNil)
            {
                if (newNode->m_Value.first < currentNode->m_Value.first)
                {
                    currentNode = currentNode->pLeft;
                }
                else if (newNode->m_Value.first > currentNode->m_Value.first)
                {
                    currentNode = currentNode->pRight;
                }
                else if (newNode->m_Value.first == currentNode->m_Value.first)
                {
                    delete newNode;
                    return { currentNode , false };;
                }
                else
                {
                    delete newNode;
                    return { currentNode , false };
                }
            }
 
            if (currentNode->pParent->pRight == currentNode)
            {
                currentNode->pParent->pRight = newNode;
                if (this->m_pMaxNode == currentNode->pParent || this->m_pMaxNode == currentNode)
                {
                    this->m_pMaxNode = newNode;
                }
                if (this->m_pMinNode == currentNode)
                {
                    this->m_pMinNode = newNode;
                }
            }
            else
            {
                currentNode->pParent->pLeft = newNode;
                if (this->m_pMinNode == currentNode->pParent || this->m_pMinNode == currentNode)
                {
                    this->m_pMinNode = newNode;
                }
                if (this->m_pMaxNode == currentNode)
                {
                    this->m_pMaxNode = newNode;
                }
            }
 
 
            newNode->pParent = currentNode->pParent;
            delete currentNode;
            this->m_iSize++;
        }
        return { in_order_iterator(newNode), true };
    }
 
    bool delete_by_key(KeyType otherKey);
 
    void clear();
 
    bool empty();
 
    int size();
 
    in_order_iterator begin()
    {
        return in_order_iterator(this->m_pMinNode);
    }
 
    in_order_iterator end()
    {
        return in_order_iterator(this->m_pMaxNode->pRight);
    }
 
    in_order_reverse_iterator rbegin()
    {
        return in_order_reverse_iterator(this->m_pMaxNode);
    }
 
    in_order_reverse_iterator rend()
    {
        return in_order_reverse_iterator(this->m_pMinNode->pLeft);
    }
 
    in_wigth_iterator iwbegin()
    {
        return in_wigth_iterator(this->m_pRoot->pRight);
    }
 
    in_wigth_iterator iwend()
    {
        return in_wigth_iterator(this->m_pMaxNode->pRight);
    }
 
private:
 
    simple_binary_tree_node* findNode(KeyType otherKey)
    {
        simple_binary_tree_node* currentNode = this->m_pRoot->pRight;
        while (!currentNode->m_isNil)
        {
            if (otherKey < currentNode->m_Value.second)
            {
                currentNode = currentNode->pLeft;
            }
            else if (otherKey > currentNode->m_Value.second)
            {
                currentNode = currentNode->pRight;
            }
            else if (otherKey == currentNode->m_Value.second)
            {
                break;
            }
            else
            {
                return this->m_pRoot;
            }
        }
        return currentNode;
    }
 
    bool deleteNode(simple_binary_tree_node* toDeleteNode)
    {
        if (toDeleteNode->m_isNil)
        {
            return false;
        }
        else
        {
            simple_binary_tree_node* deputyNode = toDeleteNode->pRight;
            if (this->m_pMaxNode == toDeleteNode)
            {
                if (toDeleteNode->pParent->m_isNil) this->m_pMaxNode = deputyNode;
                else this->m_pMaxNode = toDeleteNode->pParent;
            }
            if (this->m_pMinNode == toDeleteNode)
            {
                if (toDeleteNode->pParent->m_isNil) this->m_pMinNode = deputyNode;
                else this->m_pMinNode = toDeleteNode->pParent;
            }
            if (deputyNode->m_isNil)
            {
                delete deputyNode;
                deputyNode = toDeleteNode->pLeft;
 
                if (toDeleteNode->pParent->pLeft == toDeleteNode) toDeleteNode->pParent->pLeft = deputyNode;
                else toDeleteNode->pParent->pRight = deputyNode;
                deputyNode->pParent = toDeleteNode->pParent;
 
                delete toDeleteNode;
            }
            else
            {
                while (!deputyNode->pLeft->m_isNil)
                {
                    deputyNode = deputyNode->pLeft;
                }
                if (deputyNode->pRight->m_isNil)
                {
                    delete deputyNode->pRight;
                    deputyNode->pLeft->pParent = deputyNode->pParent;
                    if (deputyNode->pParent->pLeft == deputyNode) deputyNode->pParent->pLeft = deputyNode->pLeft;
                    else deputyNode->pParent->pRight = deputyNode->pLeft;
                }
                else
                {
                    delete deputyNode->pLeft;
                    deputyNode->pRight->pParent = deputyNode->pParent;
                    if (deputyNode->pParent->pLeft == deputyNode) deputyNode->pParent->pLeft = deputyNode->pRight;
                    else deputyNode->pParent->pRight = deputyNode->pRight;
                }
                deputyNode->pParent = toDeleteNode->pParent;
                deputyNode->pLeft = toDeleteNode->pLeft;
                deputyNode->pRight = toDeleteNode->pRight;
 
                if (toDeleteNode->pParent->pLeft == toDeleteNode) toDeleteNode->pParent->pLeft = deputyNode;
                else toDeleteNode->pParent->pRight = deputyNode;
                toDeleteNode->pLeft->pParent = deputyNode;
                toDeleteNode->pRight->pParent = deputyNode;
            }
            this->m_iSize--;
            return true;
        }
    }
 
    simple_binary_tree_node* m_pRoot;
    simple_binary_tree_node* m_pMinNode;
    simple_binary_tree_node* m_pMaxNode;
    int m_iSize;
};
 
template<typename KeyType, typename ValueType>
inline simple_binary_tree<KeyType, ValueType>::simple_binary_tree()
{
    this->m_iSize = 0;
    this->m_pRoot = simple_binary_tree_node::get_allocated_new_node();
    this->m_pRoot->m_isNil = true;
    this->m_pMinNode = this->m_pMaxNode = this->m_pRoot->pRight;
}
 
template<typename KeyType, typename ValueType>
inline simple_binary_tree<KeyType, ValueType>::~simple_binary_tree()
{
    this->clear();
    delete this->m_pRoot->pLeft;
    delete this->m_pRoot->pRight;
    delete this->m_pRoot;
}
 
 
 
template<typename KeyType, typename ValueType>
inline bool simple_binary_tree<KeyType, ValueType>::delete_by_key(KeyType otherKey)
{
    return this->deleteNode(this->findNode(otherKey));
}
 
template<typename KeyType, typename ValueType>
inline void simple_binary_tree<KeyType, ValueType>::clear()
{
    while (!this->m_pRoot->pRight->m_isNil)
    {
        deleteNode(this->m_pRoot->pRight);
    }
}
 
template<typename KeyType, typename MappedType>
inline bool simple_binary_tree<KeyType, MappedType>::empty()
{
    return this->m_pRoot->pRight->m_isNil;
}
 
template<typename KeyType, typename MappedType>
inline int simple_binary_tree<KeyType, MappedType>::size()
{
    return this->m_iSize;
}
simple_binary_tree_node
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
#pragma once
#include <utility>
 
 
template <typename KeyType, typename MappedType>
class simple_binary_tree;
 
template <typename KeyType, typename MappedType>
class simple_binary_tree_node
{
    template <typename KeyType, typename MappedType>
    friend class simple_binary_tree;
public:
    using ValueType  = std::pair<KeyType, MappedType>;
 
private:
 
    enum isNil
    {
        NODE,
        Nil
    };
 
    simple_binary_tree_node(ValueType otherValue = ValueType(),
        simple_binary_tree_node<KeyType, MappedType>* otherpParent = nullptr,
        simple_binary_tree_node<KeyType, MappedType>* otherpLeft = nullptr,
        simple_binary_tree_node<KeyType, MappedType>* otherpRight = nullptr)
    {
        this->m_isNil = NODE;
        this->m_Value = otherValue;
        this->pParent = otherpParent;
        this->pLeft = otherpLeft;
        this->pRight = otherpRight;
    }
 
    static simple_binary_tree_node<KeyType, MappedType>* get_allocated_new_node(ValueType otherValue = ValueType())
    {
        simple_binary_tree_node<KeyType, MappedType>* newNode = new simple_binary_tree_node<KeyType, MappedType>(otherValue,
            nullptr,
            new simple_binary_tree_node<KeyType, MappedType>(),
            new simple_binary_tree_node<KeyType, MappedType>());
        newNode->pLeft->pParent = newNode;
        newNode->pRight->pParent = newNode;
        newNode->pLeft->m_isNil = true;
        newNode->pRight->m_isNil = true;
        return newNode;
    }
 
    char m_isNil;
    ValueType m_Value;
    simple_binary_tree_node* pParent;
    simple_binary_tree_node* pLeft;
    simple_binary_tree_node* pRight;
 
};

Код я еще сильно не рефакторит так что сильно не пинайте).
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
20.05.2021, 21:47
Цитата Сообщение от stdin Посмотреть сообщение
Так что может у кого-нибуть будут идеи? Сама функция работает.
Если тебе нужно обходить дерево по итератору, как в std::map, то нужно будет добавить две дополнительные ноды - крайне левую и крайне правую. А лучше, просто не делай так, обходи рекурсивно, безо всяких итераторов. Твои is_begin/is_end, это очень плохая идея.
Есть ещё одна идея - формировать список одновременно с деревом. Но это только идея, реализовывать даже не пытался.

Добавлено через 1 минуту
Цитата Сообщение от stdin Посмотреть сообщение
ItType operator +(int otherStep) const
Цитата Сообщение от stdin Посмотреть сообщение
ItType operator - (int otherStep) const
Лучше убери это
0
 Аватар для stdin
129 / 81 / 49
Регистрация: 10.01.2020
Сообщений: 293
21.05.2021, 08:38  [ТС]
oleg-m1973,
Цитата Сообщение от oleg-m1973 Посмотреть сообщение
крайне левую и крайне правую
Уже есть.


Проблема тогда в таком, например я хочу использовать вставку c другого дерева от begin() до end().
Тут-то без прохода в ширину не обойдешься вот и пришлось итераторы в ширину добавить(обычный iterator идет in-order).
При in-order, т.к. это не самобалансирующееся дерево, все будет вставляться на правый узел, и это уже будет не дерево.
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
21.05.2021, 19:49
Цитата Сообщение от stdin Посмотреть сообщение
Проблема тогда в таком, например я хочу использовать вставку c другого дерева от begin() до end().
Тут-то без прохода в ширину не обойдешься вот и пришлось итераторы в ширину добавить(обычный iterator идет in-order).
А зачем итераторы? Рекурсивно нельзя сделать?
0
 Аватар для stdin
129 / 81 / 49
Регистрация: 10.01.2020
Сообщений: 293
21.05.2021, 22:47  [ТС]
oleg-m1973, можно и рекурсивно, но мне интересно итератор в ширину сделать.
0
"C with Classes"
2022 / 1404 / 523
Регистрация: 16.08.2014
Сообщений: 5,885
Записей в блоге: 1
21.05.2021, 22:53
oleg-m1973, ты не устал учить людей обходить деревья?
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
22.05.2021, 11:57
Цитата Сообщение от stdin Посмотреть сообщение
oleg-m1973, можно и рекурсивно, но мне интересно итератор в ширину сделать.
Там нет хорошего решения. Только плохие. Одно из них у тебя уже сделано. Тебя интересуют другие плохие решения?

Цитата Сообщение от _stanislav Посмотреть сообщение
oleg-m1973, ты не устал учить людей обходить деревья?
Нет, не устал. Я, вроде, никогда особо никого и не учил.
0
"C with Classes"
2022 / 1404 / 523
Регистрация: 16.08.2014
Сообщений: 5,885
Записей в блоге: 1
22.05.2021, 12:25
Цитата Сообщение от oleg-m1973 Посмотреть сообщение
особо никого и не учил.
я заметил, что ты в сложных структурах (типа налево на право) очень много тем поднимаешь.

Добавлено через 1 минуту
про ету скажи что нибудь, мне приятно будет https://github.com/stasPet/BinarySearchTree
0
 Аватар для stdin
129 / 81 / 49
Регистрация: 10.01.2020
Сообщений: 293
23.05.2021, 09:27  [ТС]
_stanislav, если в классе ноды шаблонный тип делаешь, то нет смысла делать его по умолчанию TKey k = 0, так как если TKey будет строка - выдаст ошибку, лучше сделать по умолчанию: TKey k = TKey();
Деструктор для ноды тоже не нужен, тем более класс то вложенный в класс дерева. Выделяется память под саму ноду в методах дерева, соответственно и удаляется в деструкторе дерева.
И что за загадочный pProprietor в классе ноды? Думаю, можно полностью обойтись без него.
Также, "Рекурсивное уничтожение дерева" лучше сделать в дереве, а не в ноде.
0
6772 / 4565 / 1844
Регистрация: 07.05.2019
Сообщений: 13,726
23.05.2021, 12:05
Цитата Сообщение от _stanislav Посмотреть сообщение
про ету скажи что нибудь, мне приятно будет https://github.com/stasPet/BinarySearchTree
Посмотрел. Какая-то убогая хрень. Ты ж вроде не студент, и должен понимать, что не стоит браться за задачу, если не знаешь, что ты делаешь, и зачем ты это делаешь.
0
"C with Classes"
2022 / 1404 / 523
Регистрация: 16.08.2014
Сообщений: 5,885
Записей в блоге: 1
23.05.2021, 17:53
Цитата Сообщение от oleg-m1973 Посмотреть сообщение
Какая-то убогая хрень.
можно подробней?
Цитата Сообщение от oleg-m1973 Посмотреть сообщение
ы ж вроде не студент, и должен понимать, что не стоит браться за задачу, если не знаешь, что ты делаешь, и зачем ты это делаешь.
Эта моя первая структура была написана довольно таки давно. Переписал я ее отсюда.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
BasicMan
Эксперт
29316 / 5623 / 2384
Регистрация: 17.02.2009
Сообщений: 30,364
Блог
23.05.2021, 17:53
Помогаю со студенческими работами здесь

Обход Бинарного дерева
Задача: написать функцию, помощью которой можно получить n-тый элемент бинарного дерева по возрастанию. в узлах хранятся целые числа. ...

Обход бинарного дерева
может есть у кого такой пример или похожий??или часть какая нибудь?

Обход бинарного дерева С++
Нужна помощь! Просмотрел много источников, но так и не нашёл своего ответа...Суть задачи состоит в том что, мне нужно при обходе...

Обход бинарного дерева
Прошу Вас, помогите школьнику, незнающему деревья, завтра срочно надо сдать работу, я никак не могу реализовать... 1. В заданном...

НЕрекурсивный обход бинарного дерева
уважаемые программисты! нужно написать алгоритм обхода бинарного дерева без использования рекурсии, а с помощью стека. Проверить на...


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

Или воспользуйтесь поиском по форуму:
13
Ответ Создать тему
Новые блоги и статьи
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Символьное дифференцирование
igorrr37 13.02.2026
/ * Программа принимает математическое выражение в виде строки и выдаёт его производную в виде строки и вычисляет значение производной при заданном х Логарифм записывается как: (x-2)log(x^2+2) -. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
SDL3 для Web (WebAssembly): Подключение Box2D v3, физика и отрисовка коллайдеров
8Observer8 12.02.2026
Содержание блога Box2D - это библиотека для 2D физики для анимаций и игр. С её помощью можно определять были ли коллизии между конкретными объектами и вызывать обработчики событий столкновения. . . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL_LoadPNG (без SDL3_image)
8Observer8 11.02.2026
Содержание блога Библиотека SDL3 содержит встроенные инструменты для базовой работы с изображениями - без использования библиотеки SDL3_image. Пошагово создадим проект для загрузки изображения. . .
SDL3 для Web (WebAssembly): Загрузка PNG с прозрачным фоном с помощью SDL3_image
8Observer8 10.02.2026
Содержание блога Библиотека SDL3_image содержит инструменты для расширенной работы с изображениями. Пошагово создадим проект для загрузки изображения формата PNG с альфа-каналом (с прозрачным. . .
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru