Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_tree_node.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
43#ifndef TPL_TREE_H
44#define TPL_TREE_H
45
46#include <cassert>
47#include <stdexcept>
48#include <utility>
49#include <dlink.H>
50#include <ahDry.H>
51#include <ah-dry-mixin.H>
52#include <ahIterator.H>
53#include <ahFunction.H>
54#include <ahFunctional.H>
55#include <htlist.H>
56#include <tpl_dynListStack.H>
57#include <tpl_dynListQueue.H>
58#include <tpl_binNode.H>
59#include <tpl_dfs_stack.H>
60#include <ah-errors.H>
61
62#define ISROOT(p) ((p)->is_root())
63#define ISLEAF(p) ((p)->is_leaf())
64#define ISLEFTMOST(p) ((p)->is_leftmost())
65#define ISRIGHTMOST(p) ((p)->is_rightmost())
66
67#define SIBLING_LIST(p) ((p)->get_sibling_list())
68#define CHILD_LIST(p) ((p)->get_child_list())
69#define SIBLING_LINK(p) ((p)->get_sibling_list())
70#define LCHILD(p) ((p)->get_left_child())
71#define RSIBLING(p) ((p)->get_right_sibling())
72#define IS_UNIQUE_SIBLING(p) (SIBLING_LIST(p)->is_empty())
73
74namespace Aleph {
75
76namespace tree_node_detail
77{
80 template <class Node>
81 void free_detached_tree(Node *root) noexcept;
82}
83
85template <class T>
86class Tree_Node; // Forward declaration for CRTP
87
121template <class T>
122class Tree_Node : public FunctionalMixin<Tree_Node<T>, Tree_Node<T> *>
123{
124 T data = T(); // not indeterminate in a node built by default
127
128 struct Flags
129 {
130 unsigned int is_root : 1;
131 unsigned int is_leaf : 1;
132 unsigned int is_leftmost : 1;
133 unsigned int is_rightmost : 1;
134 Flags() noexcept : is_root(1), is_leaf(1), is_leftmost(1), is_rightmost(1) {}
135 };
136
138
141
142 // It finds the nodes of a tree by their sibling links
143 template <class Node>
145
146 Tree_Node *upper_link() const noexcept
147 {
149 }
150
151 Tree_Node *lower_link() const noexcept
152 {
154 }
155
156 Tree_Node *left_link() const noexcept
157 {
159 }
160
161 Tree_Node *right_link() const noexcept
162 {
164 }
165
166public:
168
170 T &get_key() noexcept
171 {
172 return get_data();
173 }
174
175 [[nodiscard]] constexpr const T &get_key() const noexcept
176 {
177 return get_data();
178 }
179
181 T &get_data() noexcept
182 {
183 return data;
184 }
185
186 [[nodiscard]] constexpr const T &get_data() const noexcept
187 {
188 return data;
189 }
190
192 using key_type = T;
193
205 {
206 return &child;
207 }
208
221 {
222 return &sibling;
223 }
224
226 [[nodiscard]] constexpr bool is_root() const noexcept
227 {
228 return flags.is_root;
229 }
230
232 [[nodiscard]] constexpr bool is_leaf() const noexcept
233 {
234 return flags.is_leaf;
235 }
236
238 [[nodiscard]] constexpr bool is_leftmost() const noexcept
239 {
240 return flags.is_leftmost;
241 }
242
244 [[nodiscard]] constexpr bool is_rightmost() const noexcept
245 {
246 return flags.is_rightmost;
247 }
248
256 void set_is_root(bool value) noexcept
257 {
259 }
260
268 void set_is_leaf(bool value) noexcept
269 {
271 }
272
281 void set_is_leftmost(bool value) noexcept
282 {
284 }
285
293 void set_is_rightmost(bool value) noexcept
294 {
296 }
297
306 Tree_Node() = default;
307
309 Tree_Node(const T &d) : data(d)
310 { /* empty */
311 }
312
313 Tree_Node(T &&d) : data(std::move(d))
314 { /* empty */
315 }
316
318 Tree_Node *get_left_sibling() const noexcept
319 {
320 if (is_leftmost())
321 return nullptr;
322
323 return left_link();
324 }
325
327 Tree_Node *get_right_sibling() const noexcept
328 {
329 if (is_rightmost())
330 return nullptr;
331
332 return right_link();
333 }
334
336 Tree_Node *get_left_child() const noexcept
337 {
338 if (is_leaf())
339 return nullptr;
340
341 return lower_link();
342 }
343
345 Tree_Node *get_right_child() const noexcept
346 {
347 if (is_leaf())
348 return nullptr;
349
350 const Tree_Node *left_child = lower_link();
351
352 assert(ISLEFTMOST(left_child));
353
354 return left_child->left_link();
355 }
356
364 Tree_Node *get_child(const size_t i) const noexcept
365 {
367 for (size_t j = 0; c != nullptr and j < i; ++j)
368 c = c->get_right_sibling();
369
370 return c;
371 }
372
379 Tree_Node *get_parent() const noexcept
380 {
381 if (is_root())
382 return nullptr;
383
384 auto *p = const_cast<Tree_Node *>(this);
385 if (ISRIGHTMOST(p)) // the circle of siblings goes back to the first one
386 p = p->right_link();
387
388 while (not ISLEFTMOST(p)) // go down to the leftmost node
389 p = p->left_link();
390
391 assert(not ISROOT(p));
392 assert(not CHILD_LIST(p)->is_empty());
393
394 return p->upper_link();
395 }
396
407 {
408 if (p == nullptr)
409 return;
410
411 assert(CHILD_LIST(p)->is_empty());
412 assert(SIBLING_LIST(p)->is_empty());
413 assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and p->is_leaf());
414
415 if (this->is_root())
416 {
417 this->insert_tree_to_right(p);
418 return;
419 }
420
421 p->set_is_root(false);
422 p->set_is_leftmost(false);
423
424 Tree_Node *old_next_node = get_right_sibling();
425 if (old_next_node != nullptr)
426 {
427 assert(not this->is_rightmost());
428 p->set_is_rightmost(false);
429 }
430 else
431 {
432 assert(this->is_rightmost());
433 p->set_is_rightmost(true);
434 }
435
436 this->set_is_rightmost(false);
437 this->sibling.insert(SIBLING_LIST(p));
438 }
439
447 {
448 if (p == nullptr)
449 return;
450
451 ah_domain_error_if(this->is_root()) << "Cannot insert sibling of a root";
452
453 assert(CHILD_LIST(p)->is_empty());
454 assert(SIBLING_LIST(p)->is_empty());
455 assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and p->is_leaf());
456
457 p->set_is_root(false);
458 p->set_is_rightmost(false);
459
460 Tree_Node *old_prev_node = this->get_left_sibling();
461 if (old_prev_node != nullptr)
462 {
463 assert(not this->is_leftmost());
464 p->set_is_leftmost(false);
465 }
466 else
467 { // this is the leftmost ==> p must become the first child
468 assert(this->is_leftmost());
469
470 Tree_Node *parent = this->get_parent();
471
472 // Find the tree root. To do so, we look for the leaf of this
473 Tree_Node *leaf = this;
474 while (not leaf->is_leaf())
475 {
476 leaf = leaf->get_left_child();
477 assert(leaf != nullptr);
478 }
479
480 Tree_Node *root = leaf->lower_link();
481 assert(root != nullptr);
482
483 Dlink tree = CHILD_LIST(root)->cut_list(CHILD_LIST(this));
484 tree.del();
485 CHILD_LIST(parent)->insert(CHILD_LIST(p));
486 p->set_is_leftmost(true);
487
488 assert(p->get_parent() == parent);
489 }
490
491 this->set_is_leftmost(false);
492 this->sibling.append(SIBLING_LIST(p));
493 }
494
500 {
501 if (p == nullptr)
502 return;
503
504 assert(CHILD_LIST(p)->is_empty());
505 assert(SIBLING_LIST(p)->is_empty());
506 assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and p->is_leaf());
507
508 p->set_is_root(false);
509 if (this->is_leaf())
510 {
511 this->set_is_leaf(false);
512 CHILD_LIST(this)->insert(CHILD_LIST(p));
513 }
514 else
515 {
516 Tree_Node *old_left_child = this->lower_link();
517 Tree_Node *leaf = old_left_child;
518 while (not leaf->is_leaf())
519 leaf = leaf->get_left_child();
520
521 Tree_Node *root = leaf->lower_link();
522 Dlink subtree = CHILD_LIST(root)->cut_list(CHILD_LIST(old_left_child));
523 subtree.del();
524 CHILD_LIST(this)->insert(CHILD_LIST(p));
525 SIBLING_LIST(old_left_child)->append(SIBLING_LIST(p));
526 old_left_child->set_is_leftmost(false);
527 p->set_is_rightmost(false);
528 assert(p->get_right_sibling() == old_left_child);
529 assert(old_left_child->get_left_sibling() == p);
530 }
531 assert(p->is_leftmost());
532 }
533
539 {
540 if (p == nullptr)
541 return;
542
543 assert(CHILD_LIST(p)->is_empty());
544 assert(SIBLING_LIST(p)->is_empty());
545 assert(p->is_rightmost() and p->is_leftmost() and p->is_root() and p->is_leaf());
546
547 p->set_is_root(false);
548
549 if (this->is_leaf())
550 {
551 this->set_is_leaf(false);
552 CHILD_LIST(this)->insert(CHILD_LIST(p));
553 }
554 else
555 {
556 Tree_Node *old_right_child_node = this->lower_link()->left_link();
557 old_right_child_node->set_is_rightmost(false);
558 p->set_is_leftmost(false);
559 SIBLING_LIST(old_right_child_node)->insert(SIBLING_LIST(p));
560 }
561 }
562
565 {
566 assert(this->is_root());
567 assert(tree != nullptr);
568 assert(tree->is_root() and tree->is_leftmost() and tree->is_rightmost());
569
570 tree->set_is_root(false);
571
572 if (this->is_leaf())
573 {
574 assert(CHILD_LIST(this)->is_empty() and SIBLING_LIST(this)->is_empty());
575 this->set_is_leaf(false);
576 CHILD_LIST(this)->splice(CHILD_LIST(tree));
577 }
578 else
579 {
580 Tree_Node *right_child = this->lower_link()->left_link();
581 right_child->set_is_rightmost(false);
582 tree->set_is_leftmost(false);
583 SIBLING_LINK(right_child)->splice(SIBLING_LINK(tree));
584 }
585
586 return this;
587 }
588
602 {
603 if (tree == nullptr)
604 return;
605
606 ah_domain_error_if(not this->is_root()) << "\"this\" is not root";
607
608 tree->set_is_leftmost(false);
609 Tree_Node *old_next_tree = this->get_right_tree();
610 if (old_next_tree != nullptr)
611 {
612 assert(not this->is_rightmost());
613 tree->set_is_rightmost(false);
614 }
615
616 this->set_is_rightmost(false);
617 SIBLING_LIST(this)->insert(SIBLING_LIST(tree));
618 }
619
621 Tree_Node *get_left_tree() const noexcept
622 {
623 if (is_leftmost())
624 return nullptr;
625 assert(not is_leftmost());
626 return left_link();
627 }
628
630 Tree_Node *get_right_tree() const noexcept
631 {
632 if (is_rightmost())
633 return nullptr;
634
635 assert(not is_rightmost());
636 return right_link();
637 }
638
642 {
643 ah_range_error_if(not is_leftmost()) << "\"this\" is not the leftmost tree in the forest";
644
645 return left_link();
646 }
647
649 template <template <typename> class Container = DynList>
651 {
653 for (auto t = const_cast<Tree_Node *>(this); t != nullptr; t = t->get_right_tree())
654 ret.append(t);
655 return ret;
656 }
657
659 template <typename Operation>
660 void for_each_child(Operation &op) const
661 {
662 for (Tree_Node *child = get_left_child(); child != nullptr; child = child->get_right_sibling())
663 op(child);
664 }
665
666 template <typename Operation>
667 void for_each_child(Operation &&op = Operation()) const
668 {
669 for_each_child<Operation>(op);
670 }
671
673 template <template <typename> class Container = DynList>
675 {
677 this->for_each_child([&ret_val](Tree_Node *p)
678 {
679 ret_val.append(p);
680 });
681 return ret_val;
682 }
683
685 template <template <typename> class Container = DynList>
687 {
688 Container<T> ret_val;
689 this->for_each_child([&ret_val](Tree_Node *p)
690 {
691 ret_val.append(p->get_key());
692 });
693 return ret_val;
694 }
695
696private:
697 // Visits root and the nodes below it in preorder while op gives true;
698 // false if op gave false. op takes a Tree_Node *, as the operations of
699 // FunctionalMixin give it. A path can be as long as the tree is deep,
700 // too long for recursion: the next node is found through the links.
701 template <class Operation>
702 static bool preorder(const Tree_Node *root, Operation &op)
703 {
704 if (root == nullptr)
705 return true;
706
707 auto *p = const_cast<Tree_Node *>(root);
708 if (p->is_leaf())
709 return op(p);
710
711 while (true)
712 {
713 if (not op(p))
714 return false;
715
716 while (not p->is_leaf()) // down the first children, which go first
717 {
718 p = p->lower_link();
719 if (not op(p))
720 return false;
721 }
722
723 // the right sibling of p, or of its lowest ancestor below root
724 // that has one; the first sibling, to which the circle of the
725 // siblings of the last one goes back, gives the parent
726 while (p->is_rightmost())
727 {
728 p = p->right_link()->upper_link();
729 if (p == root)
730 return true;
731 }
732
733 p = p->right_link();
734 }
735 }
736
737public:
739 template <class Operation>
740 bool traverse(Operation op)
741 {
742 return preorder(this, op);
743 }
744
748 template <class Operation>
749 bool traverse(Operation op) const
750 {
751 return const_cast<Tree_Node *>(this)->traverse(op);
752 }
753
754 template <class Op>
755 bool level_traverse(Op op)
756 {
758 q.put(this);
759 while (not q.is_empty())
760 {
761 Tree_Node *p = q.get();
762 if (not op(p))
763 return false;
764 p->for_each_child([&q](auto cptr)
765 {
766 q.put(cptr);
767 });
768 }
769 return true;
770 }
771
775 template <class Op>
776 bool level_traverse(Op op) const
777 {
778 return const_cast<Tree_Node *>(this)->level_traverse(op);
779 }
780
781 // Note: for_each(), all(), exists(), maps(), filter(), foldl(),
782 // fold(), partition(), take(), drop(), rev(), length() are now
783 // provided by FunctionalMixin<Tree_Node<T>, Tree_Node<T>*>
784
789 {
790 Tree_Node *curr = nullptr;
791
792 public:
793 Children_Iterator(const Tree_Node &p) noexcept : curr(p.get_left_child()) {}
794
795 Children_Iterator(Tree_Node &p) noexcept : curr(p.get_left_child()) {}
796
797 Children_Iterator(Tree_Node *p) noexcept : curr(p->get_left_child()) {}
798
800 : curr(it.curr)
801 {}
802
803 [[nodiscard]] bool has_curr() const noexcept
804 {
805 return curr != nullptr;
806 }
807
808 Tree_Node *get_curr_ne() const noexcept
809 {
810 return curr;
811 }
812
814 {
815 ah_overflow_error_if(curr == nullptr) << "Children_Iterator::get_curr()";
816 return get_curr_ne();
817 }
818
819 void next_ne() noexcept
820 {
822 }
823
824 void next()
825 {
826 ah_overflow_error_if(curr == nullptr) << "Children_Iterator::next()";
827 next_ne();
828 }
829 };
830
832 {
833 return Children_Iterator(*this);
834 }
835
843 {
848 {
850 };
851 };
852
860 {
861 Tree_Node *root = nullptr;
862 Tree_Node *curr = nullptr;
863 long pos = 0;
865
866 public:
868
869 void swap(Iterator &it) noexcept
870 {
871 std::swap(root, it.root);
872 std::swap(curr, it.curr);
873 std::swap(pos, it.pos);
874 s.swap(it.s);
875 }
876
877 Iterator(Tree_Node *r = nullptr) noexcept : root(r), curr(root)
878 {
879 // empty
880 }
881
883
884 Iterator(const Iterator &it) : root(it.root), curr(it.curr), pos(it.pos), s(it.s)
885 {
886 // empty
887 }
888
889 Iterator(Iterator &&it) noexcept : root(nullptr), curr(nullptr), pos(0), s()
890 {
891 swap(it);
892 }
893
895 {
896 it.swap(*this);
897 return *this;
898 }
899
900 void reset_first() noexcept
901 {
902 s.empty();
903 pos = 0;
904 curr = root;
905 }
906
907 [[nodiscard]] bool has_curr() const noexcept
908 {
909 return curr != nullptr;
910 }
911
912 Tree_Node *get_curr_ne() const noexcept
913 {
914 return curr;
915 }
916
918 {
919 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
920 return get_curr_ne();
921 }
922
923 void next_ne() noexcept
924 {
925 ++pos;
926 Tree_Node *lchild = curr->get_left_child();
927 if (lchild == nullptr)
928 {
929 if (s.is_empty())
930 curr = nullptr;
931 else
932 curr = s.pop();
933
934 return;
935 }
936
937 for (auto p = curr->get_right_child(); p != lchild; p = p->get_left_sibling())
938 s.push(p);
939
940 curr = lchild;
941 }
942
943 void next()
944 {
945 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
946 next_ne();
947 }
948
949 void end()
950 {
951 curr = nullptr;
952 s.empty();
953 pos = -1;
954 }
955
957 // has_curr() == true
958 [[nodiscard]] size_t get_pos() const
959 {
960 return pos;
961 }
962 };
963
965 {
966 return Iterator(const_cast<Tree_Node *>(this));
967 }
968
970};
971
981template <typename T>
982struct Tree_Node_Vtl : public Tree_Node<T>
983{
984 virtual ~Tree_Node_Vtl() = default;
985};
986
1001template <class Node>
1002static inline void clone_tree(Node *src, Node *tgt)
1003{
1004 Node *s = src, *t = tgt;
1005 while (true)
1006 {
1007 for (Node *c = s->get_left_child(); c != nullptr; c = c->get_right_sibling())
1008 t->insert_rightmost_child(new Node(c->get_key()));
1009
1010 if (Node *child = s->get_left_child()) // its subtree goes first
1011 {
1012 s = child;
1013 t = t->get_left_child();
1014 continue;
1015 }
1016
1017 // the right sibling of s, or of its lowest ancestor below src that
1018 // has one
1019 while (s != src and s->is_rightmost())
1020 {
1021 s = s->get_parent();
1022 t = t->get_parent();
1023 }
1024
1025 if (s == src)
1026 return;
1027
1028 s = s->get_right_sibling();
1029 t = t->get_right_sibling();
1030 }
1031}
1032
1041template <class Node>
1043{
1044 if (root == nullptr)
1045 return nullptr;
1046
1047 Node *ret = new Node(root->get_key());
1048 try
1049 {
1050 clone_tree(root, ret);
1051 }
1052 catch (...)
1053 {
1054 destroy_tree(ret);
1055 throw;
1056 }
1057
1058 return ret;
1059}
1060
1061namespace tree_node_detail
1062{
1065 template <class Node>
1067 {
1069 int index;
1070 };
1071} // namespace tree_node_detail
1072
1073// Visits root and the nodes below it in preorder, as a recursion would.
1074// The ancestors of the visited node below root wait in a stack, with their
1075// positions: a path can be as long as the tree is deep, too long for
1076// recursion.
1077template <class Node>
1078static inline void __tree_preorder_traversal(Node *root, const int &level, const int &child_index,
1079 void (*visitFct)(Node *, int, int))
1080{
1082 Node *p = root;
1083 int depth = level, pos = child_index;
1084 while (true)
1085 {
1086 (*visitFct)(p, depth, pos);
1087 if (Node *child = p->get_left_child()) // its children go first
1088 {
1090 p = child;
1091 ++depth;
1092 pos = 0;
1093 continue;
1094 }
1095
1096 // the right sibling of p, or of its lowest ancestor below root that
1097 // has one
1098 while (p != root and p->is_rightmost())
1099 {
1100 p = path.top().node;
1101 pos = path.top().index;
1102 path.pop();
1103 --depth;
1104 }
1105
1106 if (p == root)
1107 return;
1108
1109 p = p->get_right_sibling();
1110 ++pos;
1111 }
1112}
1113
1139template <class Node>
1140inline void tree_preorder_traversal(Node *root, void (*visitFct)(Node *, int, int))
1141{
1142 ah_domain_error_if(not root->is_root()) << "root is not root";
1143
1144 __tree_preorder_traversal(root, 0, 0, visitFct);
1145}
1146
1172template <class Node>
1173inline void forest_preorder_traversal(Node *root, void (*visitFct)(Node *, int, int))
1174{
1175 ah_domain_error_if(not root->is_root()) << "root is not root";
1176
1177 for (/* nothing */; root != nullptr; root = root->get_right_tree())
1178 {
1179 assert(root->is_root());
1180 __tree_preorder_traversal(root, 0, 0, visitFct);
1181 }
1182}
1183
1184// Visits node and the nodes below it in postorder, as a recursion would.
1185// The ancestors of the visited node below node wait in a stack, with their
1186// positions: a path can be as long as the tree is deep, too long for
1187// recursion.
1188template <class Node>
1189static inline void __tree_postorder_traversal(Node *node, const int &level, const int &child_index,
1190 void (*visitFct)(Node *, int, int))
1191{
1193 Node *p = node;
1194 int depth = level, pos = child_index;
1195 while (true)
1196 {
1197 // down to the first leaf below p, whose visit goes first
1198 for (Node *child = p->get_left_child(); child != nullptr; child = p->get_left_child())
1199 {
1201 p = child;
1202 ++depth;
1203 pos = 0;
1204 }
1205
1206 while (true)
1207 {
1208 (*visitFct)(p, depth, pos);
1209 if (p == node)
1210 return;
1211
1212 if (not p->is_rightmost()) // the subtree of its right sibling
1213 break;
1214
1215 // the last child: its parent goes next
1216 p = path.top().node;
1217 pos = path.top().index;
1218 path.pop();
1219 --depth;
1220 }
1221
1222 p = p->get_right_sibling();
1223 ++pos;
1224 }
1225}
1226
1251template <class Node>
1252inline void tree_postorder_traversal(Node *root, void (*visitFct)(Node *, int, int))
1253{
1254 __tree_postorder_traversal(root, 0, 0, visitFct);
1255}
1256
1283template <class Node>
1284inline void forest_postorder_traversal(Node *root, void (*visitFct)(Node *, int, int))
1285{
1286 ah_domain_error_if(not root->is_leftmost()) << "root is not the leftmost node of forest";
1287
1288 ah_domain_error_if(not root->is_root()) << "root is not root";
1289
1290 for (/* nothing */; root not_eq nullptr; root = root->get_right_sibling())
1291 {
1292 assert(root->is_root());
1293 __tree_postorder_traversal(root, 0, 0, visitFct);
1294 }
1295}
1296
1313template <class Node, class Eq>
1314inline bool are_tree_equal(Node *t1, Node *t2, Eq &eq)
1315{
1316 if (t1 == nullptr)
1317 return t2 == nullptr;
1318
1319 if (t2 == nullptr)
1320 return false;
1321
1322 Node *p = t1, *q = t2;
1323 while (true)
1324 {
1325 if (not eq(p->get_key(), q->get_key()))
1326 return false;
1327
1328 Node *a = p->get_left_child(), *b = q->get_left_child();
1329 while (a != nullptr and b != nullptr) // as many children
1330 {
1331 a = a->get_right_sibling();
1332 b = b->get_right_sibling();
1333 }
1334
1335 if (a != b)
1336 return false;
1337
1338 if (Node *child = p->get_left_child()) // their subtrees go first
1339 {
1340 p = child;
1341 q = q->get_left_child();
1342 continue;
1343 }
1344
1345 // the right siblings of p and q, or of their lowest ancestors that
1346 // have them
1347 while (p != t1 and p->is_rightmost())
1348 {
1349 p = p->get_parent();
1350 q = q->get_parent();
1351 }
1352
1353 if (p == t1)
1354 return true;
1355
1356 p = p->get_right_sibling();
1357 q = q->get_right_sibling();
1358 }
1359}
1360
1361template <class Node, class Eq = std::equal_to<typename Node::key_type>>
1362inline bool are_tree_equal(Node *t1, Node *t2, Eq &&eq = Eq())
1363{
1364 return are_tree_equal<Node, Eq>(t1, t2, eq);
1365}
1366
1367namespace tree_node_detail
1368{
1369 /* Frees root and every node below it. root has no parent nor siblings,
1370 and the nodes below it are not linked with others: the links among
1371 them, which are left as they are, need not keep the invariants of the
1372 class while they go. The roots of the subtrees that wait to go are kept
1373 in a list, by their sibling links: when a node goes, its children,
1374 which a circle of sibling links already joins, join the list as a
1375 whole. */
1376 // GCC 12 and on warn that the address of pending, a local list, is
1377 // stored in root, as the list links it; the list is empty again before
1378 // the function ends, so that nothing dangles. GCC 11 does not know the
1379 // warning.
1380#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12
1381# pragma GCC diagnostic push
1382# pragma GCC diagnostic ignored "-Wdangling-pointer"
1383#endif
1384 template <class Node>
1386 {
1388
1389 Dlink pending;
1390 pending.append(SIBLING_LIST(root));
1391 while (not pending.is_empty())
1392 {
1393 auto *p = static_cast<Node *>(Base::sibling_to_Tree_Node(pending.remove_next()));
1394 if (not p->is_leaf())
1395 {
1396 Dlink children; // the header of the circle of the children of p
1397 children.wrap_header(SIBLING_LIST(p->get_left_child()));
1398 pending.concat_list(children);
1399 }
1400 delete p;
1401 }
1402 }
1403#if defined(__GNUC__) && !defined(__clang__) && __GNUC__ >= 12
1404# pragma GCC diagnostic pop
1405#endif
1406
1407 /* Takes root, with the nodes below it, out of its tree, or out of its
1408 forest if root is a tree of one: what is left is as if root had not
1409 been inserted. If root is the leftmost child, its right sibling takes
1410 its place, and the spine of that sibling goes below the parent (see
1411 the class-level note); if root is the only child, the parent becomes
1412 a leaf. */
1413 template <class Node>
1414 void detach_tree(Node *root) noexcept
1415 {
1416 if (not root->is_root() and root->is_leftmost())
1417 {
1418 // root and its leftmost descendants leave the spine of the parent:
1419 // they are from root to the leaf at the bottom of the spine
1420 auto *parent = root->get_parent();
1421 Node *leaf = root;
1422 while (not leaf->is_leaf())
1423 leaf = static_cast<Node *>(leaf->get_left_child());
1424
1425 Dlink *top = CHILD_LIST(leaf)->get_next(); // of the spine of parent
1426 Dlink below = top->cut_list(CHILD_LIST(root));
1427 below.del();
1428
1430 parent->set_is_leaf(true);
1431 else
1432 {
1433 auto *next = root->get_right_sibling();
1434 next->set_is_leftmost(true);
1435 CHILD_LIST(parent)->splice(CHILD_LIST(next));
1436 SIBLING_LIST(root)->del();
1437 }
1438 }
1439 else if (not IS_UNIQUE_SIBLING(root))
1440 {
1441 // a sibling that is not the leftmost child, or a tree of a forest
1442 if (root->is_rightmost())
1443 root->get_left_sibling()->set_is_rightmost(true);
1444 if (root->is_leftmost())
1445 root->get_right_sibling()->set_is_leftmost(true);
1446 SIBLING_LIST(root)->del();
1447 }
1448 }
1449} // namespace tree_node_detail
1450
1464template <class Node>
1466{
1467 if (root == nullptr)
1468 return;
1469
1472}
1473
1485template <class Node>
1487{
1488 if (root == nullptr)
1489 return;
1490
1491 ah_domain_error_if(not root->is_leftmost()) << "root is not the leftmost tree of forest";
1492
1493 ah_domain_error_if(not root->is_root()) << "root is not root";
1494
1495 while (root != nullptr) // traverse trees from left to right
1496 {
1497 Node *to_delete = root; // backup root
1498 root = (Node *) root->get_right_sibling(); // advance to next tree
1499 SIBLING_LIST(to_delete)->del(); // remove from tree list
1500 destroy_tree(to_delete); // delete the tree
1501 }
1502}
1503
1510template <class Node>
1512{
1513 if (root == nullptr)
1514 return 0;
1515
1516 // In preorder, with the depth of each node. A path can be as long as the
1517 // tree is deep, too long for recursion: the parent of a node is found
1518 // through its left siblings and its first child.
1519 size_t depth = 1, height = 1;
1520 Node *p = root;
1521 while (true)
1522 {
1523 if (auto *child = static_cast<Node *>(p->get_left_child()))
1524 {
1525 p = child;
1526 if (++depth > height)
1527 height = depth;
1528 continue;
1529 }
1530
1531 // the right sibling of p, or of its lowest ancestor below root that
1532 // has one
1533 while (p != root and p->is_rightmost())
1534 {
1535 p = static_cast<Node *>(p->get_parent());
1536 --depth;
1537 }
1538
1539 if (p == root)
1540 return height;
1541
1542 p = static_cast<Node *>(p->get_right_sibling());
1543 }
1544}
1545
1546// Follows the positions of path from idx on, a level at a time, from node
1547template <class Node>
1548static inline Node *__deway_search(Node *node, int path[], const int &idx, const size_t &size)
1549{
1550 for (int level = idx; node != nullptr; ++level)
1551 {
1552 ah_out_of_range_error_if(static_cast<size_t>(level) >= size) << "index out of maximum range";
1553
1554 if (path[level] < 0) // check whether the node has been reached
1555 return node;
1556
1557 // advance to the child path[level]
1558 Node *child = node->get_left_child();
1559 for (int i = 0; i < path[level] and child != nullptr; ++i)
1560 child = child->get_right_sibling();
1561
1562 node = child; // next level
1563 }
1564
1565 return nullptr;
1566}
1567
1581template <class Node>
1582inline Node *deway_search(Node *root, int path[], const size_t &size)
1583{
1584 for (int i = 0; root != nullptr; i++, root = root->get_right_sibling())
1585 if (path[0] == i)
1586 return __deway_search(root, path, 1, size);
1587
1588 return nullptr;
1589}
1590
1591template <class Node, class Equal>
1592inline static Node *__search_deway(Node *root, const typename Node::key_type &key,
1593 const size_t &current_level, int deway[], const size_t &size,
1594 size_t &n);
1595
1616template <class Node, class Equal = Aleph::equal_to<typename Node::key_type>>
1617inline Node *search_deway(Node *root, const typename Node::key_type &key, int deway[],
1618 const size_t &size, size_t &n)
1619{
1620 n = 1; // initial length value of the Dewey number
1621
1622 ah_overflow_error_if(size < n) << "there is no enough space for deway array";
1623
1624 for (int i = 0; root != nullptr; i++, root = root->get_right_sibling())
1625 {
1626 deway[0] = i;
1627 Node *result = __search_deway<Node, Equal>(root, key, 0, deway, size, n);
1628 if (result != nullptr)
1629 return result;
1630 }
1631
1632 return nullptr;
1633}
1634
1635// Searches key in preorder below root, as a recursion would; deway holds
1636// the positions of the nodes of the path. A path can be as long as the
1637// tree is deep, too long for recursion: the parent of a node is found
1638// through its left siblings and its first child.
1639template <class Node, class Equal>
1640inline static Node *__search_deway(Node *root, const typename Node::key_type &key,
1641 const size_t &current_level, int deway[], const size_t &size,
1642 size_t &n)
1643{
1644 ah_overflow_error_if(current_level >= size) << "there is no enough space for deway array";
1645
1646 if (root == nullptr)
1647 return nullptr;
1648
1649 Node *p = root;
1650 size_t level = current_level;
1651 while (true)
1652 {
1653 if (Equal()(p->get_key(), key))
1654 {
1655 n = level + 1; // length of the deway array
1656 return p;
1657 }
1658
1659 if (Node *child = p->get_left_child()) // its children go first
1660 {
1661 ah_overflow_error_if(level + 1 >= size) << "there is no enough space for deway array";
1662 deway[level + 1] = 0;
1663 p = child;
1664 ++level;
1665 continue;
1666 }
1667
1668 // the right sibling of p, or of its lowest ancestor below root that
1669 // has one
1670 while (p != root and p->is_rightmost())
1671 {
1672 p = p->get_parent();
1673 --level;
1674 }
1675
1676 if (p == root)
1677 return nullptr;
1678
1679 p = p->get_right_sibling();
1680 ++deway[level];
1681 }
1682}
1683
1684namespace tree_node_detail
1685{
1687 template <class TNode, class BNode>
1689 {
1690 TNode *tnode;
1691 BNode *bnode;
1692 };
1693
1696 template <class BNode>
1697 void free_bin_tree(BNode *root) noexcept
1698 {
1699 while (root != BNode::NullPtr)
1700 if (LLINK(root) != BNode::NullPtr)
1701 {
1702 BNode *left = LLINK(root);
1703 LLINK(root) = RLINK(left);
1704 RLINK(left) = root;
1705 root = left;
1706 }
1707 else
1708 {
1709 BNode *right = RLINK(root);
1710 delete root;
1711 root = right;
1712 }
1713 }
1714} // namespace tree_node_detail
1715
1739template <class TNode, class BNode>
1740BNode *forest_to_bin(TNode *root)
1741{
1742 if (root == nullptr)
1743 return BNode::NullPtr;
1744
1745 auto *result = new BNode(root->get_key());
1746 try
1747 {
1748 // The nodes of the path whose right siblings wait, with their
1749 // binary nodes
1751 TNode *p = root;
1752 BNode *b = result;
1753 while (true)
1754 {
1755 if (TNode *child = p->get_left_child()) // its children go first
1756 {
1757 auto *bchild = new BNode(child->get_key());
1758 LLINK(b) = bchild;
1760 p = child;
1761 b = bchild;
1762 continue;
1763 }
1764
1765 // the right sibling of p, or of its lowest ancestor that has one
1766 while (p->is_rightmost() and not path.is_empty())
1767 {
1768 p = path.top().tnode;
1769 b = path.top().bnode;
1770 path.pop();
1771 }
1772
1773 if (p->is_rightmost())
1774 return result;
1775
1776 TNode *sibling = p->get_right_sibling();
1777 auto *bsibling = new BNode(sibling->get_key());
1778 RLINK(b) = bsibling;
1779 p = sibling;
1780 b = bsibling;
1781 }
1782 }
1783 catch (...)
1784 {
1786 throw;
1787 }
1788}
1789
1790template <class TNode, class BNode>
1791inline static void insert_child(BNode *lnode, TNode *tree_node)
1792{
1793 if (lnode == BNode::NullPtr)
1794 return;
1795
1796 auto *child = new TNode(KEY(lnode));
1797 tree_node->insert_leftmost_child(child);
1798}
1799
1800template <class TNode, class BNode>
1801inline static void insert_sibling(BNode *rnode, TNode *tree_node)
1802{
1803 if (rnode == BNode::NullPtr)
1804 return;
1805
1806 auto *sibling = new TNode(KEY(rnode));
1807 tree_node->insert_right_sibling(sibling);
1808}
1809
1810// Makes the children and the right siblings of troot from the subtrees of
1811// broot, in the order of a recursion. The binary nodes whose right
1812// subtrees wait for their left ones are kept in a stack, with the nodes
1813// made of them: a path can be as long as the binary tree is deep, too long
1814// for recursion.
1815template <class TNode, class BNode>
1816inline static void bin_to_tree(BNode *broot, TNode *troot)
1817{
1818 if (broot == BNode::NullPtr)
1819 return;
1820
1822 BNode *b = broot;
1823 TNode *t = troot;
1824 while (true)
1825 {
1826 if (LLINK(b) != BNode::NullPtr) // the left subtree goes first
1827 {
1828 insert_child(LLINK(b), t);
1830 t = t->get_left_child();
1831 b = LLINK(b);
1832 continue;
1833 }
1834
1835 // the right subtree of b, or of the lowest one that waits
1836 while (RLINK(b) == BNode::NullPtr)
1837 {
1838 if (pending.is_empty())
1839 return;
1840
1841 t = pending.top().tnode;
1842 b = pending.top().bnode;
1843 pending.pop();
1844 }
1845
1846 insert_sibling(RLINK(b), t);
1847 t = t->get_right_sibling();
1848 b = RLINK(b);
1849 }
1850}
1851
1873template <class TNode, class BNode>
1874inline TNode *bin_to_forest(BNode *broot)
1875{
1876 if (broot == BNode::NullPtr)
1877 return nullptr;
1878
1879 auto *troot = new TNode(KEY(broot));
1880 try
1881 {
1882 bin_to_tree(broot, troot);
1883 }
1884 catch (...)
1885 {
1886 destroy_forest(troot);
1887 throw;
1888 }
1889
1890 return troot;
1891}
1892
1893} // end namespace Aleph
1894
1895#endif // TPL_TREE_H
CRTP Mixins for container functionality (DRY principle).
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_domain_error_if(C)
Throws std::domain_error if condition holds.
Definition ah-errors.H:670
#define ah_range_error_if(C)
Throws std::range_error if condition holds.
Definition ah-errors.H:356
DRY (Don't Repeat Yourself) utilities and macros.
Standard functor implementations and comparison objects.
Functional programming utilities for Aleph-w containers.
Iterator traits and STL-compatible iterator wrappers.
#define STL_ALEPH_ITERATOR(Set_Name)
Definition ahIterator.H:208
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
size_t size_t int32_t value
Definition ca-c-api.h:116
Stack of the frames of a depth-first search that does not recurse.
T & push(Args &&...args)
Builds a frame on top of the stack.
bool is_empty() const noexcept
Whether the stack has no frames.
T & top() noexcept
The top frame; the stack must not be empty.
void pop() noexcept
Destroys the top frame; the stack must not be empty.
Dynamic queue of elements of generic type T based on single linked list.
T & put(const T &data)
The type of element.
T get()
Remove the oldest item of the queue.
bool is_empty() const noexcept
Return true if this is empty.
Dynamic stack of elements of generic type T based on a singly linked list.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
CRTP Mixin providing functional programming operations.
and
Transform elements using a mapping function.
Iterator over the children of this.
Children_Iterator(const Children_Iterator &it) noexcept
Children_Iterator(Tree_Node &p) noexcept
Children_Iterator(const Tree_Node &p) noexcept
Children_Iterator(Tree_Node *p) noexcept
Tree_Node * get_curr_ne() const noexcept
Preorder iterator over a tree rooted at a Tree_Node.
Iterator(const Iterator &it)
bool has_curr() const noexcept
Iterator(Iterator &&it) noexcept
Iterator & operator=(Iterator it)
void swap(Iterator &it) noexcept
size_t get_pos() const
Return the current position of the iterator. Only valid if.
Iterator(Tree_Node *r=nullptr) noexcept
Tree_Node * get_curr() const
DynListStack< Tree_Node * > s
Tree_Node * get_curr_ne() const noexcept
Forward declaration used by CRTP helpers before the full node definition.
Tree_Node(const T &d)
Constructor with data value __data.
constexpr bool is_leftmost() const noexcept
Returns true if this is the leftmost node among its siblings.
bool traverse(Operation op)
Preorder traversal over all nodes executing op.
void set_is_root(bool value) noexcept
Sets the root flag.
Dlink * get_sibling_list() noexcept
Returns the embedded sibling-list link.
Tree_Node * left_link() const noexcept
Tree_Node * upper_link() const noexcept
static Tree_Node * sibling_to_Tree_Node(Dlink *link) noexcept
Tree_Node * join(Tree_Node *tree)
join tree as subtree of root this
Tree_Node * get_last_tree() const
Returns the rightmost tree of the forest containing this.
void insert_left_sibling(Tree_Node *p)
Inserts p as the left sibling of this.
Tree_Node * get_left_sibling() const noexcept
Returns the left sibling of this.
Tree_Node()=default
Constructor of a node whose key is T(): zero for an arithmetic type or a pointer.
constexpr const T & get_key() const noexcept
bool level_traverse(Op op) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
constexpr bool is_root() const noexcept
Returns true if this is the root of the general tree.
bool level_traverse(Op op)
T key_type
Generic data type stored in the node.
Tree_Node * get_left_child() const noexcept
Returns the leftmost child of this.
constexpr bool is_rightmost() const noexcept
Returns true if this is the rightmost node among its siblings.
Tree_Node * right_link() const noexcept
static bool preorder(const Tree_Node *root, Operation &op)
static Tree_Node * child_to_Tree_Node(Dlink *link) noexcept
Tree_Node * get_child(const size_t i) const noexcept
Returns the i-th child of this.
Container< Tree_Node * > trees() const
Return a list with all trees belonging to the forest.
void insert_leftmost_child(Tree_Node *p) noexcept
Inserts p as the leftmost child of this.
constexpr bool is_leaf() const noexcept
Returns true if this is a leaf node.
T & get_data() noexcept
Returns a modifiable reference to the node contents.
Dlink * get_child_list() noexcept
Returns the embedded child-list link.
Tree_Node * get_right_sibling() const noexcept
Returns the right sibling of this.
Tree_Node * get_left_tree() const noexcept
Returns the tree to the left of this.
void insert_rightmost_child(Tree_Node *p) noexcept
Inserts p as the rightmost child of this.
Tree_Node * lower_link() const noexcept
Children_Iterator children_it() const
Tree_Node * get_right_tree() const noexcept
Returns the tree to the right of this.
void insert_tree_to_right(Tree_Node *tree)
Insert tree to the right of this
constexpr const T & get_data() const noexcept
Tree_Node * get_parent() const noexcept
Returns the parent of this.
void set_is_leaf(bool value) noexcept
Sets the leaf flag.
Container< Tree_Node * > children_nodes() const
Returns a list with the child nodes of this.
void for_each_child(Operation &op) const
Visits each child of this and executes the operation on the child node.
bool traverse(Operation op) const
This is an overloaded member function, provided for convenience. It differs from the above function o...
Tree_Node * get_right_child() const noexcept
Returns the rightmost child of this.
void insert_right_sibling(Tree_Node *p) noexcept
Inserts p to the right of this node.
T & get_key() noexcept
Returns a modifiable reference to the node contents.
Iterator get_it() const
Container< T > children() const
Returns a list with the contents of the children of this.
void set_is_leftmost(bool value) noexcept
Sets the leftmost-sibling flag.
void for_each_child(Operation &&op=Operation()) const
void set_is_rightmost(bool value) noexcept
Sets the rightmost-sibling flag.
void deway(Tree_Node< int > *p, int prefix[], const int &len, const size_t &dim)
Recursively compute and print Deway numbering for a tree node.
Definition deway.C:118
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
void forest_postorder_traversal(Node *root, void(*visitFct)(Node *, int, int))
Postorder traversal of a forest.
void destroy_tree(Node *root)
Destroys (frees memory) the tree whose root is root.
size_t compute_height(Node *root)
Computes the height of the tree root.
void tree_postorder_traversal(Node *root, void(*visitFct)(Node *, int, int))
Postorder traversal of a tree.
static void clone_tree(Node *src, Node *tgt)
Copies the subtrees of the children of src as children of tgt.
TNode * bin_to_forest(BNode *broot)
Converts a binary tree to its equivalent forest.
bool are_tree_equal(Node *t1, Node *t2, Eq &eq)
Returns true if t1 is equal to t2.
void destroy_forest(Node *root)
Destroys (frees memory) the forest whose first tree is root.
void forest_preorder_traversal(Node *root, void(*visitFct)(Node *, int, int))
Preorder traversal of a forest.
void tree_preorder_traversal(Node *root, void(*visitFct)(Node *, int, int))
Preorder traversal of a tree.
Node * search_deway(Node *root, const typename Node::key_type &key, int deway[], const size_t &size, size_t &n)
Searches key in a forest and computes the Dewey number of the node containing the key.
Node * deway_search(Node *root, int path[], const size_t &size)
Returns a node of a forest given its Dewey number.
BNode * forest_to_bin(TNode *root)
Converts a forest to its equivalent binary tree.
Singly linked list implementations with head-tail access.
void free_detached_tree(Node *root) noexcept
Frees a tree that has no parent nor siblings, without recursion; it finds the nodes by their sibling ...
void detach_tree(Node *root) noexcept
void free_bin_tree(BNode *root) noexcept
Frees the binary tree root without recursion nor memory: a node with a left child turns into the righ...
Main namespace for Aleph-w library functions.
static Node * __deway_search(Node *node, int path[], const int &idx, const size_t &size)
static void insert_sibling(BNode *rnode, TNode *tree_node)
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
static void insert_child(BNode *lnode, TNode *tree_node)
static Node * __search_deway(Node *root, const typename Node::key_type &key, const size_t &current_level, int deway[], const size_t &size, size_t &n)
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
static void bin_to_tree(BNode *broot, TNode *troot)
static void __tree_postorder_traversal(Node *node, const int &level, const int &child_index, void(*visitFct)(Node *, int, int))
static void __tree_preorder_traversal(Node *root, const int &level, const int &child_index, void(*visitFct)(Node *, int, int))
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Child iterator adapter used by generic iterator utilities.
Adapter that exposes a node's children through an Iterator type.
Children_Set(const Tree_Node &)
Children_Set(const Tree_Node &&)
Tree_Node variant with a virtual destructor.
virtual ~Tree_Node_Vtl()=default
A node of a forest and its node in the binary tree.
BNode * bnode
Its node in the binary tree.
TNode * tnode
The node of the forest.
A node of a path that a traversal follows, and its position among its siblings.
int index
Its position among its siblings.
#define RLINK(i, n)
#define LLINK(i, n)
DynArray< int > preorder
Gsl_Compatible_Rng r
Basic binary tree node definitions.
Stack of the frames of a depth-first search that does not recurse.
Dynamic queue implementation based on linked lists.
Dynamic stack implementation based on linked lists.
#define SIBLING_LINK(p)
#define SIBLING_LIST(p)
#define ISROOT(p)
#define CHILD_LIST(p)
#define IS_UNIQUE_SIBLING(p)
#define ISLEFTMOST(p)
#define ISRIGHTMOST(p)