Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_binNodeUtils.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
42#ifndef TPL_BINNODEUTILS_H
43#define TPL_BINNODEUTILS_H
44
45# include <ah-concepts.H>
46
47#include <ahFunction.H>
48#include <tpl_arrayStack.H>
49#include <tpl_small_vector.H>
50#include <tpl_arrayQueue.H>
51#include <tpl_dynListQueue.H>
52#include <bitArray.H>
53#include <tpl_dynDlist.H>
54#include <tpl_binNode.H>
55#include <ah-errors.H>
56# include <cassert>
57# include <type_traits>
58# include <utility>
59
60namespace Aleph {
61
80template <class Fct, class... Args>
81inline constexpr bool nothrow_condition_v =
82 std::is_nothrow_invocable_r_v<bool, Fct, Args...> and
83 requires { { static_cast<bool>(std::declval<Fct>()(std::declval<Args>()...)) } noexcept; };
84
92template <class Cmp, class Key>
93inline constexpr bool nothrow_compare_keys_v =
94 nothrow_condition_v<Cmp, const Key &, const Key &> and
95 nothrow_condition_v<Cmp, const Key &, Key &> and
96 nothrow_condition_v<Cmp, Key &, const Key &> and
97 nothrow_condition_v<Cmp, Key &, Key &>;
98
119template <class Compare, class Key>
120inline constexpr bool nothrow_compare_v =
121 nothrow_compare_keys_v<Compare &, Key> and
122 nothrow_compare_keys_v<const Compare &, Key>;
123
134template <class Compare, class Key>
135inline constexpr bool nothrow_compare_copy_v =
136 nothrow_compare_v<Compare, Key> and
137 std::is_nothrow_constructible_v<Compare, Compare &> and
138 std::is_nothrow_constructible_v<Compare, const Compare &>;
139
155template <BinNodeLike Node>
156inline void assert_valid_tree_root([[maybe_unused]] const Node *root) noexcept
157{
158 assert((Node::NullPtr == nullptr or root != nullptr) and
159 "nullptr is not an empty tree for a node type with a sentinel; use Node::NullPtr");
160}
161template <BinNodeLike Node>
162inline void inorder_rec_helper(Node *node, const int &level, int &position,
163 void (*visitFct)(Node *, int, int))
164{
165 if (node == Node::NullPtr)
166 return;
167
168 inorder_rec_helper(LLINK(node), level + 1, position, visitFct);
169
170 (*visitFct)(node, level, position);
171 ++position;
172
173 inorder_rec_helper(RLINK(node), level + 1, position, visitFct);
174}
175
198template <BinNodeLike Node>
199inline int inOrderRec(Node *root, void (*visitFct)(Node *, int, int))
200{
202 int position = 0;
203 inorder_rec_helper(root, 0, position, visitFct);
204 return position;
205}
206
207template <BinNodeLike Node>
208inline void preorder_rec_helper(Node *p, const int &level, int &position,
209 void (*visitFct)(Node *, int, int))
210{
211 if (p == Node::NullPtr)
212 return;
213
214 (*visitFct)(p, level, position);
215 ++position;
216
217 preorder_rec_helper(LLINK(p), level + 1, position, visitFct);
218 preorder_rec_helper(RLINK(p), level + 1, position, visitFct);
219}
220
243template <BinNodeLike Node>
244inline int preOrderRec(Node *root, void (*visitFct)(Node *, int, int))
245{
247 int position = 0;
248 preorder_rec_helper(root, 0, position, visitFct);
249 return position;
250}
251
252template <BinNodeLike Node>
253inline void postorder_rec_helper(Node *node, const int &level, int &position,
254 void (*visitFct)(Node *, int, int))
255{
256 if (node == Node::NullPtr)
257 return;
258
259 postorder_rec_helper(LLINK(node), level + 1, position, visitFct);
260 postorder_rec_helper(RLINK(node), level + 1, position, visitFct);
261
262 (*visitFct)(node, level, position);
263 ++position;
264}
265
288template <BinNodeLike Node>
289inline int postOrderRec(Node *root, void (*visitFct)(Node *, int, int))
290{
292 int position = 0;
293 postorder_rec_helper(root, 0, position, visitFct);
294 return position;
295}
296
312template <class Node>
314{
315 template <class Op>
316 static void for_each_inorder(Node *root, Op &&op)
317 {
318 if (root == Node::NullPtr)
319 return;
320
321 for_each_inorder(LLINK(root), std::forward<Op>(op));
322 op(root);
323 for_each_inorder(RLINK(root), std::forward<Op>(op));
324 }
325
326public:
328 template <class Op>
329 void traverse(Node *root, Op &&op) const
330 {
331 for_each_inorder(root, std::forward<Op>(op));
332 }
333
335 template <class Op>
336 void operator () (Node *root, Op &op) const
337 {
339 }
340
342 template <class Op>
343 void operator () (Node *root, Op &&op) const
344 {
345 for_each_inorder(root, std::forward<Op>(op));
346 }
347};
348
355template <BinNodeLike Node, class Op>
356inline void for_each_in_order(Node *root, Op &&op)
357{
358 return For_Each_In_Order<Node>().traverse(root, std::forward<Op>(op));
359}
360
377template <class Node>
379{
380 template <class Op>
381 static void preorder(Node *root, Op &&op)
382 {
383 if (root == Node::NullPtr)
384 return;
385
386 op(root);
387 preorder(LLINK(root), std::forward<Op>(op));
388 preorder(RLINK(root), std::forward<Op>(op));
389 }
390
391public:
393 template <class Op>
394 void traverse(Node *root, Op &&op) const
395 {
396 return preorder(root, std::forward<Op>(op));
397 }
398
400 template <class Op>
401 void operator () (Node *root, Op &op) const
402 {
403 preorder(root, op);
404 }
405
407 template <class Op>
408 void operator () (Node *root, Op &&op = Op()) const
409 {
410 preorder(root, std::forward<Op>(op));
411 }
412};
413
420template <BinNodeLike Node, class Op>
422{
423 For_Each_Preorder<Node>().traverse(root, std::forward<Op>(op));
424}
425
441template <class Node>
443{
444 template <class Op>
445 static void postorder(Node *root, Op &&op)
446 {
447 if (root == Node::NullPtr)
448 return;
449
450 postorder(LLINK(root), std::forward<Op>(op));
451 postorder(RLINK(root), std::forward<Op>(op));
452 op(root);
453 }
454
455public:
457 template <class Op>
458 void traverse(Node *root, Op &&op) const
459 {
460 return postorder(root, std::forward<Op>(op));
461 }
462
464 template <class Op>
465 void operator () (Node *root, Op &op) const
466 {
467 postorder(root, op);
468 }
469
471 template <class Op>
472 void operator () (Node *root, Op &&op = Op()) const
473 {
474 postorder(root, std::forward<Op>(op));
475 }
476};
477
484template <BinNodeLike Node, class Op>
486{
487 For_Each_Postorder<Node>().traverse(root, std::forward<Op>(op));
488}
489
490template <BinNodeLike Node>
491static void prefix(Node *root, DynList<Node *> &acc)
492{
493 if (root == Node::NullPtr)
494 return;
495
496 acc.append(root);
497 prefix(LLINK(root), acc);
498 prefix(RLINK(root), acc);
499}
500
501template <BinNodeLike Node>
502static void infix(Node *root, DynList<Node *> &acc)
503{
504 if (root == Node::NullPtr)
505 return;
506
507 infix(LLINK(root), acc);
508 acc.append(root);
509 infix(RLINK(root), acc);
510}
511
512template <BinNodeLike Node>
513static void suffix(Node *root, DynList<Node *> &acc)
514{
515 if (root == Node::NullPtr)
516 return;
517
518 suffix(LLINK(root), acc);
519 suffix(RLINK(root), acc);
520 acc.append(root);
521}
522
530template <BinNodeLike Node>
532{
533 DynList<Node *> ret_val;
534 prefix(root, ret_val);
535 return ret_val;
536}
537
545template <BinNodeLike Node>
547{
548 DynList<Node *> ret_val;
549 infix(root, ret_val);
550 return ret_val;
551}
552
560template <BinNodeLike Node>
562{
563 DynList<Node *> ret_val;
564 suffix(root, ret_val);
565 return ret_val;
566}
567
574template <BinNodeLike Node>
575inline size_t compute_cardinality_rec(Node *root) noexcept
576{
578 if (root == Node::NullPtr)
579 return 0;
580
582}
583
585template <BinNodeLike Node>
586inline size_t size(Node *root) noexcept
587{
589}
590
600inline constexpr size_t Bin_Tree_Depth_Bound = 128;
601
612template <BinNodeLike Node>
613inline size_t compute_height_with_stack(Node *root) noexcept
614{
615 if (root == Node::NullPtr)
616 return 0;
617
618 // each entry is a subtree that remains to be visited and its depth
620 pending.push_back(std::pair<Node *, size_t>(root, 1));
621
622 size_t height = 0;
623 while (not pending.is_empty())
624 {
625 auto [p, depth] = pending.remove_last();
626
627 // go down the left branch and defer the right subtrees
628 for (; p != Node::NullPtr; p = LLINK(p), ++depth)
629 if (Node *r = RLINK(p); r != Node::NullPtr)
630 pending.push_back(std::pair<Node *, size_t>(r, depth + 1));
631
632 height = std::max(height, depth - 1); // depth of the last node visited
633 }
634
635 return height;
636}
637
649template <BinNodeLike Node>
650inline size_t compute_height_bounded(Node *root, const size_t levels) noexcept
651{
652 if (root == Node::NullPtr)
653 return 0;
654
655 if (levels == 0) [[unlikely]]
657
658 // both links are read before going down, so that the two loads overlap
659 Node *l = LLINK(root);
660 Node *r = RLINK(root);
661 const size_t left_height = l == Node::NullPtr ? 0 : compute_height_bounded(l, levels - 1);
662 const size_t right_height = r == Node::NullPtr ? 0 : compute_height_bounded(r, levels - 1);
663
664 return 1 + std::max(left_height, right_height);
665}
666
680template <BinNodeLike Node>
681inline size_t computeHeightRec(Node *root) noexcept
682{
684
686}
687
706template <BinNodeLike Node, class Dispose>
707inline void dispose_tree_by_link_inversion(Node *root, Dispose & dispose) noexcept
708{
709 if (root == Node::NullPtr)
710 return;
711
712 Node *parent = Node::NullPtr; // of p; each ancestor keeps its own in LLINK
713 Node *p = root;
714 while (true)
715 {
716 // Go down to a leaf, first by the left, leaving in each node the way
717 // back to its parent.
718 while (true)
719 {
720 Node *child = LLINK(p);
721 if (child == Node::NullPtr)
722 {
723 child = RLINK(p);
724 if (child == Node::NullPtr)
725 break;
726 RLINK(p) = Node::NullPtr; // the right subtree is the one in course
727 }
728 LLINK(p) = parent;
729 parent = p;
730 p = child;
731 }
732
733 // Nothing hangs from p. Dispose of it and go up while the node reached
734 // has no right subtree left; otherwise that subtree is the next one.
735 while (true)
736 {
737 dispose(p);
738 if (parent == Node::NullPtr)
739 return;
740
741 p = parent;
742 parent = LLINK(p);
743 Node *r = RLINK(p);
744 LLINK(p) = Node::NullPtr;
745 if (r == Node::NullPtr)
746 continue;
747
748 RLINK(p) = Node::NullPtr;
749 LLINK(p) = parent;
750 parent = p;
751 p = r;
752 break;
753 }
754 }
755}
756
773template <BinNodeLike Node, class Dispose>
774inline void dispose_tree_nodes(Node *root, Dispose & dispose,
775 const size_t levels = Bin_Tree_Depth_Bound) noexcept
776{
777 if (root == Node::NullPtr)
778 return;
779
780 if (levels == 0) [[unlikely]]
781 {
783 return;
784 }
785
786 dispose_tree_nodes(LLINK(root), dispose, levels - 1);
787 dispose_tree_nodes(RLINK(root), dispose, levels - 1);
788 LLINK(root) = RLINK(root) = Node::NullPtr; // what hung from them is gone
789 dispose(root);
790}
791
807template <BinNodeLike Node>
808inline void destroyRec(Node *&root) noexcept
809{
811
812 const auto free_node = [] (Node *p) noexcept { delete p; };
813 dispose_tree_nodes(root, free_node);
814 root = Node::NullPtr;
815}
816
834template <BinNodeLike Node>
835inline void callKeyDestructorsRec(Node *&root) noexcept
836{
838
839 using Key = typename Node::key_type;
840
841 const auto destroy_key = [] (Node *p) noexcept { p->get_key().~Key(); };
842 dispose_tree_nodes(root, destroy_key);
843 root = Node::NullPtr;
844}
845
858template <BinNodeLike Node>
859[[nodiscard]] inline Node *copyRec(Node *root)
860{
862 if (root == Node::NullPtr)
863 return Node::NullPtr;
864
865 Node *tgt_root = Node::NullPtr;
866
867 try
868 {
869 // Each entry is a source subtree that remains to be copied and the
870 // link of the copy where it must hang.
872 pending.push_back(std::pair<Node *, Node **>(root, &tgt_root));
873
874 while (not pending.is_empty())
875 {
876 auto [src, link] = pending.remove_last();
877
878 // Go down the left branch and defer the right subtrees, which
879 // copies the nodes in preorder, as a recursion would. A copy
880 // hangs from its link as soon as it exists, so that the tree of
881 // tgt_root owns every node if something throws.
882 for (; src != Node::NullPtr; src = LLINK(src))
883 {
884 Node *tgt = new Node(*src);
885 *link = tgt;
886 if (Node *r = RLINK(src); r != Node::NullPtr)
887 pending.push_back(std::pair<Node *, Node **>(r, &RLINK(tgt)));
888 link = &LLINK(tgt);
889 }
890 }
891 }
892 catch (...)
893 {
894 destroyRec(tgt_root);
895 throw;
896 }
897
898 return tgt_root;
899}
900
911template <BinNodeLike Node>
912inline bool areSimilar(Node *t1, Node *t2) noexcept
913{
914 if (t1 == t2) // that include the case when t1 and t2 are the same
915 // or both are Node::NullPtr
916 return true;
917
918 if (t1 == Node::NullPtr or t2 == Node::NullPtr)
919 return false;
920
921 return areSimilar(LLINK(t1), LLINK(t2)) and areSimilar(RLINK(t1), RLINK(t2));
922}
923
935template <BinNodeLike Node, class Equal>
936inline bool areEquivalents(Node *t1, Node *t2, Equal &op) noexcept
937{
938 if (t1 == t2)
939 return true;
940
941 if (t1 == Node::NullPtr or t2 == Node::NullPtr)
942 return false;
943
944 if (not op(KEY(t1), KEY(t2)))
945 return false;
946
947 return areEquivalents(LLINK(t1), LLINK(t2), op) and areEquivalents(RLINK(t1), RLINK(t2), op);
948}
949
951template <BinNodeLike Node, class Equal = std::equal_to<typename Node::key_type>>
952inline bool areEquivalents(Node *t1, Node *t2, Equal &&op = Equal()) noexcept
953{
954 return areEquivalents(t1, t2, op);
955}
956
973template <BinNodeLike Node>
974inline void levelOrder(Node *root, void (*visitFct)(Node *, int, bool))
975{
977 if (root == Node::NullPtr)
978 return;
979
981 queue.put(std::pair<Node *, bool>(root, bool()));
982
983 for (int pos = 0; not queue.is_empty(); pos++)
984 {
985 std::pair<Node *, bool> pr = queue.get();
986 Node *&p = pr.first;
987
988 (*visitFct)(p, pos, pr.second);
989
990 if (LLINK(p) != Node::NullPtr)
991 queue.put(std::pair<Node *, bool>(LLINK(p), true));
992
993 if (RLINK(p) != Node::NullPtr)
994 queue.put(std::pair<Node *, bool>(RLINK(p), false));
995 }
996}
997
1013template <BinNodeLike Node, class Operation>
1014inline bool level_traverse(Node *root, Operation &operation)
1015{
1016 if (root == Node::NullPtr)
1017 return true;
1018
1020 queue.put(root);
1021 while (not queue.is_empty())
1022 {
1023 Node *p = queue.get();
1024 if (not operation(p))
1025 return false;
1026
1027 if (LLINK(p) != Node::NullPtr)
1028 queue.put(LLINK(p));
1029
1030 if (RLINK(p) != Node::NullPtr)
1031 queue.put(RLINK(p));
1032 }
1033 return true;
1034}
1035
1036template <BinNodeLike Node, class Operation>
1037inline bool level_traverse(Node *root, Operation &&operation)
1038{
1039 return level_traverse<Node, Operation>(root, operation);
1040}
1041
1057template <template <class> class Node, typename Key>
1058inline Node<Key> *build_tree(const DynArray<Key> &preorder, long l_p, long r_p,
1059 const DynArray<Key> &inorder, long l_i, long r_i)
1060{
1061 if (l_p > r_p)
1062 {
1063 assert(l_i > r_i);
1064 return Node<Key>::NullPtr;
1065 }
1066
1067 assert(r_p - l_p == r_i - l_i);
1068
1069 auto *root = new Node<Key>(preorder[l_p]);
1070 if (r_p == l_p)
1071 return root;
1072
1073 assert(l_i <= r_i);
1074
1075 // Find root key position in inorder array
1076 int i = -1;
1077 for (int j = l_i; j <= r_i; ++j)
1078 if (inorder[j] == preorder[l_p])
1079 {
1080 i = j - l_i;
1081 break;
1082 }
1083
1084 // Validate that root key was found in inorder array
1085 ah_domain_error_if(i < 0) << "build_tree: root key not found in inorder array (corrupted input)";
1086
1087 assert(i <= r_i - l_i);
1088
1089 LLINK(root) = build_tree<Node, Key>(preorder, l_p + 1, l_p + i, inorder, l_i, l_i + (i - 1));
1090 RLINK(root) = build_tree<Node, Key>(preorder, l_p + i + 1, r_p, inorder, l_i + i + 1, r_i);
1091 return root;
1092}
1093
1094template <template <class> class Node, typename Key>
1095inline Node<Key> *build_postorder(const DynArray<Key> &post, long lp, long rp,
1096 const DynArray<Key> &in, long li, long ri)
1097{
1098 assert(rp - lp == ri - li);
1099 if (lp > rp)
1100 return Node<Key>::NullPtr;
1101
1102 auto *root = new Node<Key>(post[rp]);
1103
1104 // Search in inorder array the index of root
1105 int i = li;
1106 for (; i <= ri; ++i)
1107 if (in[i] == post[rp])
1108 break;
1109
1110 // Validate that root key was found in inorder array
1111 ah_domain_error_if(i > ri)
1112 << "build_postorder: root key not found in inorder array (corrupted input)";
1113
1114 assert(i <= ri);
1115
1116 LLINK(root) = build_postorder<Node, Key>(post, lp, lp + (i - li) - 1, in, li, i - 1);
1117 RLINK(root) = build_postorder<Node, Key>(post, rp - (ri - i), rp - 1, in, i + 1, ri);
1118 return root;
1119}
1120
1121template <BinNodeLike Node>
1122inline void compute_nodes_in_level_helper(Node *root, long level, const long current_level,
1123 DynDlist<Node *> &level_list)
1124{
1125 if (root == Node::NullPtr)
1126 return;
1127
1128 if (current_level == level)
1129 {
1130 level_list.append(root);
1131 return; // it is not worth descending further
1132 }
1133
1134 compute_nodes_in_level_helper(LLINK(root), level, current_level + 1, level_list);
1135 compute_nodes_in_level_helper(RLINK(root), level, current_level + 1, level_list);
1136}
1137
1146template <BinNodeLike Node>
1148{
1149 DynDlist<Node *> list;
1150 compute_nodes_in_level_helper(root, level, 0, list);
1151 return list;
1152}
1153
1174template <BinNodeLike Node>
1175inline void inOrderThreaded(Node *root, void (*visitFct)(Node *))
1176{
1177 if (root == Node::NullPtr)
1178 return;
1179
1180 Node *p = root, *r = Node::NullPtr;
1181 while (p != Node::NullPtr)
1182 {
1183 Node *q = LLINK(p);
1184 if (q == Node::NullPtr)
1185 { // No left branch ==> visit p
1186 (*visitFct)(p);
1187 r = p;
1188 p = RLINK(p);
1189 continue;
1190 }
1191
1192 // Move towards the rightmost node of the left branch
1193 while (q != r and RLINK(q) != Node::NullPtr)
1194 q = RLINK(q);
1195
1196 if (q != r) // Does p have a predecessor?
1197 { // yes ==> leave a thread in order to later come back and visit p
1198 RLINK(q) = p; // place the thread here
1199 p = LLINK(p); // keep descending on the left
1200 continue;
1201 }
1202
1203 (*visitFct)(p);
1204
1205 RLINK(q) = Node::NullPtr; // delete thread
1206 r = p;
1207 p = RLINK(p); // advance to the right branch
1208 }
1209}
1210
1231template <BinNodeLike Node>
1232inline void preOrderThreaded(Node *node, void (*visitFct)(Node *))
1233{
1234 if (node == Node::NullPtr)
1235 return;
1236
1237 Node *p = node, *r = Node::NullPtr;
1238 while (p != Node::NullPtr)
1239 {
1240 Node *q = LLINK(p);
1241
1242 if (q == Node::NullPtr)
1243 {
1244 (*visitFct)(p);
1245 r = p;
1246 p = RLINK(p);
1247 continue;
1248 }
1249
1250 // advance towards the rightmost node of the left branch
1251 while (q != r and RLINK(q) != Node::NullPtr)
1252 q = RLINK(q);
1253
1254 if (q != r)
1255 {
1256 RLINK(q) = p;
1257 (*visitFct)(p);
1258 p = LLINK(p);
1259 continue;
1260 }
1261
1262 RLINK(q) = Node::NullPtr; /* delete thread */
1263 r = p;
1264 p = RLINK(p); /* advance to right branch */
1265 }
1266}
1267
1268template <BinNodeLike Node>
1269inline size_t internal_path_length_helper(Node *p, const size_t &level) noexcept
1270{
1271 if (p == Node::NullPtr)
1272 return 0;
1273
1274 return level + internal_path_length_helper(LLINK(p), level + 1) +
1275 internal_path_length_helper(RLINK(p), level + 1);
1276}
1277
1285template <BinNodeLike Node>
1286inline size_t internal_path_length(Node *p) noexcept
1287{
1289 return internal_path_length_helper(p, 0);
1290}
1291
1305template <BinNodeLike Node>
1306inline void tree_to_bits(Node *root, BitArray &array)
1307{
1308 if (root == Node::NullPtr)
1309 {
1310 array.push(1);
1311 return;
1312 }
1313
1314 array.push(0);
1315 tree_to_bits(LLINK(root), array);
1316 tree_to_bits(RLINK(root), array);
1317}
1318
1332template <BinNodeLike Node>
1334{
1335 BitArray ret_val;
1336 tree_to_bits(root, ret_val);
1337 return ret_val;
1338}
1339
1347template <BinNodeLike Node>
1348inline std::string code(Node *root)
1349{
1350 const BitArray bits = tree_to_bits(root);
1351 const size_t n = bits.size();
1352 std::string str;
1353 str.reserve(n);
1354 for (size_t i = 0; i < n; ++i)
1355 str.push_back(bits(i) ? 'b' : 'a');
1356
1357 return str;
1358}
1359
1360template <BinNodeLike Node>
1361inline Node *bits_to_tree_helper(const BitArray &array, int &i)
1362{
1363 // Bounds check: ensure we don't read past the end of the bit array
1364 ah_domain_error_if(i >= static_cast<int>(array.size()))
1365 << "bits_to_tree_helper: bit array index out of bounds (malformed input)";
1366
1367 if (const int bit = array.read_bit(i++); bit == 1)
1368 return Node::NullPtr;
1369
1370 Node *p = new Node;
1371 Node *left = Node::NullPtr;
1372 Node *right = Node::NullPtr;
1373 try
1374 {
1375 left = bits_to_tree_helper<Node>(array, i);
1376 right = bits_to_tree_helper<Node>(array, i);
1377 }
1378 catch (...)
1379 {
1380 destroyRec(left);
1381 destroyRec(right);
1382 delete p;
1383 throw;
1384 }
1385
1386 LLINK(p) = left;
1387 RLINK(p) = right;
1388
1389 return p;
1390}
1391
1405template <BinNodeLike Node>
1406inline Node *bits_to_tree(const BitArray &array, int idx = 0)
1407{
1408 return bits_to_tree_helper<Node>(array, idx);
1409}
1410
1428template <BinNodeLike Node>
1429inline void save_tree_keys_in_prefix(Node *root, std::ostream &output)
1430{
1431 if (root == Node::NullPtr)
1432 return;
1433
1434 output << root->get_key() << " ";
1435
1438}
1439
1450template <BinNodeLike Node>
1451inline void load_tree_keys_in_prefix(Node *root, std::istream &input)
1452{
1453 if (root == Node::NullPtr)
1454 return;
1455
1456 input >> root->get_key();
1457 ah_runtime_error_if(not input) << "load_tree_keys_in_prefix: input stream error";
1458
1461}
1462
1477template <BinNodeLike Node>
1478inline void save_tree(Node *root, std::ostream &output)
1479{
1482 prefix.save(output);
1484}
1485
1497template <BinNodeLike Node>
1498inline Node *load_tree(std::istream &input)
1499{
1501 prefix.load(input);
1502 Node *root = bits_to_tree<Node>(prefix);
1503 try
1504 {
1506 }
1507 catch (...)
1508 {
1509 destroyRec(root); // Cleanup partially loaded tree on exception
1510 throw;
1511 }
1512 return root;
1513}
1514
1515template <BinNodeLike Node, class Get_Key>
1516inline void put_tree_keys_in_array(Node *root, std::ostream &out)
1517{
1518 if (root == Node::NullPtr)
1519 return;
1520
1521 const std::string str = Get_Key()(root);
1522 out << "\"";
1523 for (const char ch : str)
1524 {
1525 switch (ch)
1526 {
1527 case '\n':
1528 out << "\\n";
1529 break;
1530 case '\t':
1531 out << "\\t";
1532 break;
1533 case '\\':
1534 out << "\\\\";
1535 break;
1536 case '"':
1537 out << "\\\"";
1538 break;
1539 default:
1540 out << ch;
1541 break;
1542 }
1543 }
1544 out << "\", ";
1545
1546 put_tree_keys_in_array<Node, Get_Key>(LLINK(root), out);
1547 put_tree_keys_in_array<Node, Get_Key>(RLINK(root), out);
1548}
1549
1550template <BinNodeLike Node, class Load_Key>
1551inline void load_tree_keys_from_array(Node *root, const char *keys[], int &idx)
1552{
1553 if (root == Node::NullPtr)
1554 return;
1555
1556 if (Load_Key()(root, keys[idx]))
1557 ++idx;
1558
1559 load_tree_keys_from_array<Node, Load_Key>(LLINK(root), keys, idx);
1560 load_tree_keys_from_array<Node, Load_Key>(RLINK(root), keys, idx);
1561}
1562
1591template <BinNodeLike Node, class Get_Key>
1592inline void save_tree_in_array_of_chars(Node *root, const std::string &array_name,
1593 std::ostream &output)
1594{
1597 prefix.save_in_array_of_chars(array_name + "_cdp", output);
1598 output << "const char * " << array_name << "_k[] = { " << '\n';
1599 put_tree_keys_in_array<Node, Get_Key>(root, output);
1600 output << "nullptr };" << '\n';
1601}
1602
1632template <BinNodeLike Node, class Load_Key>
1633inline Node *load_tree_from_array(const unsigned char bits[], const size_t &num_bits,
1634 const char *keys[])
1635{
1638 Node *root = bits_to_tree<Node>(prefix);
1639 int i = 0;
1640 load_tree_keys_from_array<Node, Load_Key>(root, keys, i);
1641 return root;
1642}
1643
1644template <BinNodeLike Node, class Compare>
1645inline bool check_bst_range(Node *p, const typename Node::key_type *min_key,
1646 const typename Node::key_type *max_key, const Compare &cmp)
1647{
1648 if (p == Node::NullPtr)
1649 return true;
1650
1651 const auto &key = KEY(p);
1652 if (min_key != nullptr and not less_or_equal_than(*min_key, key, cmp))
1653 return false;
1654 if (max_key != nullptr and not less_or_equal_than(key, *max_key, cmp))
1655 return false;
1656
1657 return check_bst_range<Node, Compare>(LLINK(p), min_key, &key, cmp) and
1658 check_bst_range<Node, Compare>(RLINK(p), &key, max_key, cmp);
1659}
1660
1670template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1671inline bool check_bst(Node *p, const Compare &cmp = Compare())
1672{
1674 return check_bst_range<Node, Compare>(p, nullptr, nullptr, cmp);
1675}
1676
1688template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1690 const Compare &cmp = Compare())
1691{
1692 if (l > r)
1693 return Node::NullPtr;
1694
1695 Node *root = new Node(preorder[l]);
1696
1697 if (l == r)
1698 return root;
1699
1700 int first_greater = l + 1;
1701 while ((first_greater <= r) and cmp(preorder[first_greater], preorder[l]))
1702 ++first_greater;
1703
1704 LLINK(root) = preorder_to_bst<Node, Compare>(preorder, l + 1, first_greater - 1, cmp);
1705 RLINK(root) = preorder_to_bst<Node, Compare>(preorder, first_greater, r, cmp);
1706
1707 return root;
1708}
1709
1711enum ThreeWayCmp : int
1712{
1713 CmpLess = -1,
1715 CmpGreater = 1
1717
1732template <typename T, class Compare = Aleph::less<T>>
1733inline ThreeWayCmp three_way_compare(const T &a, const T &b, const Compare &cmp = Compare())
1734 noexcept(nothrow_compare_v<Compare, T>)
1735{
1736 if (cmp(a, b))
1737 return CmpLess;
1738 if (cmp(b, a))
1739 return CmpGreater;
1740 return CmpEqual;
1741}
1742
1759template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1760[[nodiscard]] inline Node *searchInBinTree(Node *root, const typename Node::key_type &key,
1761 const Compare &cmp = Compare())
1762 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
1763{
1765 Node *candidate = nullptr; // Tracks potential match when going right
1766
1767 while (root != Node::NullPtr)
1768 {
1769 __builtin_prefetch(LLINK(root));
1770 __builtin_prefetch(RLINK(root));
1771
1772 if (cmp(key, KEY(root))) // key < root: go left
1773 root = LLINK(root);
1774 else // key >= root: go right, mark as candidate
1775 {
1776 candidate = root;
1777 root = RLINK(root);
1778 }
1779 }
1780
1781 // Optimistic check: if candidate exists and key == candidate, return it
1782 if (candidate != nullptr and not static_cast<bool>(cmp(KEY(candidate), key))) [[unlikely]]
1783 return candidate;
1784
1785 return Node::NullPtr;
1786}
1787
1796template <BinNodeLike Node>
1797[[nodiscard]] inline Node *find_min(Node *root) noexcept
1798{
1800 assert(root != Node::NullPtr && "find_min called on empty tree");
1801 while (LLINK(root) != Node::NullPtr)
1802 root = LLINK(root);
1803
1804 return root;
1805}
1806
1815template <BinNodeLike Node>
1816[[nodiscard]] inline Node *find_max(Node *root) noexcept
1817{
1819 assert(root != Node::NullPtr && "find_max called on empty tree");
1820 while (RLINK(root) != Node::NullPtr)
1821 root = RLINK(root);
1822
1823 return root;
1824}
1825
1834template <BinNodeLike Node>
1835inline Node *find_successor(Node *p, Node *&pp) noexcept
1836{
1837 assert(p != Node::NullPtr);
1838 assert(RLINK(p) != Node::NullPtr);
1839
1840 pp = p;
1841 p = RLINK(p);
1842 while (LLINK(p) != Node::NullPtr)
1843 {
1844 pp = p;
1845 p = LLINK(p);
1846 }
1847
1848 return p;
1849}
1850
1859template <BinNodeLike Node>
1860inline Node *find_predecessor(Node *p, Node *&pp) noexcept
1861{
1862 assert(p != Node::NullPtr);
1863 assert(LLINK(p) != Node::NullPtr);
1864
1865 pp = p;
1866 p = LLINK(p);
1867
1868 while (RLINK(p) != Node::NullPtr)
1869 {
1870 pp = p;
1871 p = RLINK(p);
1872 }
1873
1874 return p;
1875}
1876
1893template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1894inline Node *search_parent(Node *root, const typename Node::key_type &key, Node *&parent,
1895 const Compare &cmp = Compare())
1896 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
1897{
1899 assert((LLINK(parent) == root) or (RLINK(parent) == root));
1900 assert(root != Node::NullPtr);
1901
1902 while (true)
1903 {
1904 const auto c = three_way_compare(key, KEY(root), cmp);
1905 if (c == CmpLess) [[likely]]
1906 {
1907 if (LLINK(root) == Node::NullPtr)
1908 return root;
1909
1910 parent = root;
1911 root = LLINK(root);
1912 }
1913 else if (c == CmpGreater) [[likely]]
1914 {
1915 if (RLINK(root) == Node::NullPtr)
1916 return root;
1917
1918 parent = root;
1919 root = RLINK(root);
1920 }
1921 else [[unlikely]]
1922 return root;
1923 }
1924}
1925
1948template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1949inline Node *search_rank_parent(Node *root, const typename Node::key_type &key,
1950 const Compare &cmp = Compare())
1951 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
1952{
1954 assert(root != Node::NullPtr);
1955
1956 while (true)
1957 if (const auto &root_key = KEY(root); cmp(key, root_key))
1958 {
1959 if (LLINK(root) == Node::NullPtr)
1960 return root;
1961
1962 root = LLINK(root);
1963 }
1964 else if (cmp(root_key, key))
1965 {
1966 if (RLINK(root) == Node::NullPtr)
1967 return root;
1968
1969 root = RLINK(root);
1970 }
1971 else
1972 return root;
1973}
1974
1987template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
1988inline Node *insert_in_bst(Node *&r, Node *p, const Compare &cmp = Compare()) noexcept
1989{
1991 if (r == Node::NullPtr) [[unlikely]]
1992 return r = p;
1993
1994 const auto &pk = KEY(p);
1995 const auto &rk = KEY(r);
1996
1997 if (cmp(pk, rk))
1998 return insert_in_bst<Node, Compare>(LLINK(r), p, cmp);
1999 if (cmp(rk, pk))
2000 return insert_in_bst<Node, Compare>(RLINK(r), p, cmp);
2001
2002 [[unlikely]] return Node::NullPtr;
2003}
2004
2017template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2018inline Node *insert_dup_in_bst(Node *&root, Node *p, const Compare &cmp = Compare()) noexcept
2019{
2021 if (root == Node::NullPtr) [[unlikely]]
2022 return root = p;
2023
2024 const auto &pk = KEY(p);
2025 const auto &rk = KEY(root);
2026
2027 if (cmp(pk, rk))
2028 return insert_dup_in_bst(LLINK(root), p, cmp);
2029
2030 return insert_dup_in_bst(RLINK(root), p, cmp);
2031}
2032
2047template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2048inline Node *search_or_insert_in_bst(Node *&r, Node *p, const Compare &cmp = Compare()) noexcept
2049{
2051 if (r == Node::NullPtr) [[unlikely]]
2052 return r = p;
2053
2054 const auto &pk = KEY(p);
2055 const auto &rk = KEY(r);
2056
2057 if (cmp(pk, rk))
2058 return search_or_insert_in_bst<Node, Compare>(LLINK(r), p, cmp);
2059 if (cmp(rk, pk))
2060 return search_or_insert_in_bst<Node, Compare>(RLINK(r), p, cmp);
2061
2062 [[unlikely]] return r;
2063}
2064
2080template <BinNodeLike Node, class Compare>
2081inline bool split_key_rec_helper(Node *root, const typename Node::key_type &key, Node *&ts,
2082 Node *&tg, Compare &cmp)
2083 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
2084{
2085 if (root == Node::NullPtr)
2086 { // key is not in the tree ==> split will succeed
2087 ts = tg = Node::NullPtr;
2088 return true;
2089 }
2090
2091 if (cmp(key, KEY(root)))
2092 {
2093 if (split_key_rec_helper(LLINK(root), key, ts, LLINK(root), cmp))
2094 {
2095 tg = root;
2096 return true;
2097 }
2098 return false;
2099 }
2100
2101 if (cmp(KEY(root), key))
2102 if (split_key_rec_helper(RLINK(root), key, RLINK(root), tg, cmp))
2103 {
2104 ts = root;
2105 return true;
2106 }
2107
2108 return false; // key exists in the tree
2109}
2110
2134template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2135inline bool split_key_rec(Node *&root, const typename Node::key_type &key, Node *&ts, Node *&tg,
2136 const Compare &cmp = Compare())
2137 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
2138{
2140 const bool ret = split_key_rec_helper(root, key, ts, tg, cmp);
2141 if (ret)
2142 root = Node::NullPtr;
2143 return ret;
2144}
2145
2161template <BinNodeLike Node, class Compare>
2162inline void split_key_dup_rec_helper(Node *root, const typename Node::key_type &key,
2163 Node *&ts, Node *&tg, Compare &cmp)
2164 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
2165{
2166 if (root == Node::NullPtr)
2167 {
2168 ts = tg = Node::NullPtr;
2169 return;
2170 }
2171
2172 if (cmp(KEY(root), key))
2173 {
2175 ts = root;
2176 }
2177 else
2178 {
2180 tg = root;
2181 }
2182}
2183
2202template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2203inline void split_key_dup_rec(Node *&root, const typename Node::key_type &key, Node *&ts, Node *&tg,
2204 const Compare &cmp = Compare())
2205 noexcept(nothrow_compare_v<Compare, typename Node::key_type>)
2206{
2208 split_key_dup_rec_helper(root, key, ts, tg, cmp);
2209 root = Node::NullPtr;
2210}
2211
2225template <BinNodeLike Node>
2226inline Node *join_exclusive(Node *&ts, Node *&tg) noexcept
2227{
2228 if (ts == Node::NullPtr)
2229 return tg;
2230
2231 if (tg == Node::NullPtr)
2232 return ts;
2233
2234 LLINK(tg) = join_exclusive(RLINK(ts), LLINK(tg));
2235
2236 RLINK(ts) = tg;
2237 Node *ret_val = ts;
2238 ts = tg = Node::NullPtr; // empty the trees
2239
2240 return ret_val;
2241}
2242
2254template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2255inline Node *remove_from_bst(Node *&root, const typename Node::key_type &key,
2256 const Compare &cmp = Compare()) noexcept
2257{
2259 if (root == Node::NullPtr)
2260 return Node::NullPtr;
2261
2262 if (cmp(key, KEY(root)))
2263 return remove_from_bst(LLINK(root), key, cmp);
2264 if (cmp(KEY(root), key))
2265 return remove_from_bst(RLINK(root), key, cmp);
2266
2267 Node *ret_val = root; // save root that is going to be removed
2269
2270 ret_val->reset();
2271
2272 return ret_val;
2273}
2274
2289template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2290inline Node *insert_root(Node *&root, Node *p, const Compare &cmp = Compare()) noexcept
2291{
2293 Node *l = Node::NullPtr, *r = Node::NullPtr;
2294
2295 if (not split_key_rec(root, KEY(p), l, r, cmp))
2296 return Node::NullPtr;
2297
2298 LLINK(p) = l;
2299 RLINK(p) = r;
2300 root = p;
2301
2302 return root;
2303}
2304
2315template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2316inline Node *insert_dup_root(Node *&root, Node *p, const Compare &cmp = Compare()) noexcept
2317{
2319 split_key_dup_rec(root, KEY(p), LLINK(p), RLINK(p), cmp);
2320 return root = p;
2321}
2322
2336template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2337inline Node *join_preorder(Node *t1, Node *t2, Node *&dup, const Compare &cmp = Compare()) noexcept
2338{
2339 if (t2 == Node::NullPtr)
2340 return t1;
2341
2342 Node *l = LLINK(t2);
2343 Node *r = RLINK(t2);
2344
2345 t2->reset();
2346
2347 if (insert_in_bst(t1, t2, cmp) == Node::NullPtr)
2348 insert_in_bst(dup, t2, cmp); // insertion has failed
2349
2350 join_preorder(t1, l, dup, cmp);
2351 join_preorder(t1, r, dup, cmp);
2352
2353 return t1;
2354}
2355
2370template <BinNodeLike Node, class Compare = Aleph::less<typename Node::key_type>>
2371inline Node *join(Node *t1, Node *t2, Node *&dup, const Compare &cmp = Compare()) noexcept
2372{
2373 if (t1 == Node::NullPtr)
2374 return t2;
2375
2376 if (t2 == Node::NullPtr)
2377 return t1;
2378
2379 Node *l = LLINK(t1);
2380 Node *r = RLINK(t1);
2381
2382 t1->reset();
2383
2384 while (t1 != Node::NullPtr and insert_root(t2, t1, cmp) == Node::NullPtr)
2385 {
2386 Node *p = remove_from_bst(t1, KEY(t1), cmp);
2387
2388 assert(p != Node::NullPtr);
2389
2390 insert_in_bst(dup, p, cmp);
2391 }
2392
2393 LLINK(t2) = join(l, LLINK(t2), dup, cmp);
2394 RLINK(t2) = join(r, RLINK(t2), dup, cmp);
2395
2396 return t2;
2397}
2398
2404template <BinNodeLike Node>
2405inline Node *rotate_to_right(Node *p) noexcept
2406{
2407 assert(p != Node::NullPtr);
2408
2409 Node *q = LLINK(p);
2410 LLINK(p) = RLINK(q);
2411 RLINK(q) = p;
2412
2413 return q;
2414}
2415
2423template <BinNodeLike Node>
2424inline Node *rotate_to_right(Node *p, Node *pp) noexcept
2425{
2426 assert(p != Node::NullPtr);
2427 assert(pp != Node::NullPtr);
2428 assert(LLINK(pp) == p or RLINK(pp) == p);
2429
2430 Node *q = LLINK(p);
2431 LLINK(p) = RLINK(q);
2432 RLINK(q) = p;
2433
2434 if (LLINK(pp) == p) // update the parent
2435 LLINK(pp) = q;
2436 else
2437 RLINK(pp) = q;
2438
2439 return q;
2440}
2441
2447template <BinNodeLike Node>
2448inline Node *rotate_to_left(Node *p) noexcept
2449{
2450 assert(p != Node::NullPtr);
2451
2452 Node *q = RLINK(p);
2453 RLINK(p) = LLINK(q);
2454 LLINK(q) = p;
2455
2456 return q;
2457}
2458
2465template <BinNodeLike Node>
2466inline Node *rotate_to_left(Node *p, Node *pp) noexcept
2467{
2468 assert(p != Node::NullPtr);
2469 assert(pp != Node::NullPtr);
2470 assert(LLINK(pp) == p or RLINK(pp) == p);
2471
2472 Node *q = RLINK(p);
2473 RLINK(p) = LLINK(q);
2474 LLINK(q) = p;
2475
2476 // update the parent
2477 if (LLINK(pp) == p)
2478 LLINK(pp) = q;
2479 else
2480 RLINK(pp) = q;
2481
2482 return q;
2483}
2484
2499template <BinNodeLike Node, class Key, class Compare = Aleph::less<typename Node::key_type>>
2500inline void split_key(Node *&root, const Key &key, Node *&l, Node *&r,
2501 const Compare &cmp = Compare()) noexcept
2502{
2504 assert(l == Node::NullPtr and r == Node::NullPtr);
2505 if (root == Node::NullPtr)
2506 {
2507 l = r = Node::NullPtr;
2508 return;
2509 }
2510
2511 Node **current_parent = nullptr;
2512 Node **pending_child = nullptr;
2513 bool current_is_right = true;
2514 if (cmp(key, KEY(root)))
2515 {
2516 r = root;
2517 pending_child = &l;
2518 }
2519 else
2520 {
2521 l = root;
2522 pending_child = &r;
2523 current_is_right = false;
2524 }
2525
2526 Node *current = root;
2527 while (current != Node::NullPtr)
2528 {
2529 if (cmp(key, KEY(current)))
2530 { /* current must be in right side */
2531 if (not current_is_right)
2532 {
2533 current_is_right = not current_is_right;
2534 *pending_child = *current_parent; /* change of side */
2535 pending_child = current_parent;
2536 }
2537 current_parent = &LLINK(current);
2538 }
2539 else
2540 { /* current must be in left side */
2541 if (current_is_right)
2542 {
2543 current_is_right = not current_is_right;
2544 *pending_child = *current_parent; /* change of side */
2545 pending_child = current_parent;
2546 }
2547 current_parent = &RLINK(current);
2548 }
2549 current = *current_parent;
2550 }
2551 *pending_child = Node::NullPtr;
2552 root = Node::NullPtr;
2553}
2554
2564template <BinNodeLike Node>
2565inline void swap_node_with_successor(Node *p, // Node for swapping
2566 Node *&pp, // parent of p
2567 Node *q, // Successor inorder of p
2568 Node *&pq) // parent of q
2569 noexcept
2570{
2571 assert(p != Node::NullPtr and q != Node::NullPtr and pp != Node::NullPtr and pq != Node::NullPtr);
2572 assert(LLINK(pp) == p or RLINK(pp) == p);
2573 assert(LLINK(pq) == q or RLINK(pq) == q);
2574 assert(LLINK(q) == Node::NullPtr);
2575
2576 /* Set of pp to its new son q */
2577 if (LLINK(pp) == p)
2578 LLINK(pp) = q;
2579 else
2580 RLINK(pp) = q;
2581
2582 LLINK(q) = LLINK(p);
2583 LLINK(p) = Node::NullPtr;
2584
2585 /* Checks if successor is right child of p. In this case, p will
2586 become q's son. This situation happens when p's son does not have
2587 a left branch */
2588 if (RLINK(p) == q)
2589 {
2590 RLINK(p) = RLINK(q);
2591 RLINK(q) = p;
2592 pq = pp;
2593 pp = q;
2594 return;
2595 }
2596
2597 /* In this case, successor is the leftmost node descending from
2598 right son of p */
2599 Node *qr = RLINK(q);
2600 RLINK(q) = RLINK(p);
2601 LLINK(pq) = p;
2602 RLINK(p) = qr;
2603
2604 std::swap(pp, pq);
2605}
2606
2616template <BinNodeLike Node>
2617inline void swap_node_with_predecessor(Node *p, // Node for swapping
2618 Node *&pp, // p's parent
2619 Node *q, // Predecessor inorder of p
2620 Node *&pq) // q's parent
2621 noexcept
2622{
2623 assert((p != Node::NullPtr) and (q != Node::NullPtr) and (pp != Node::NullPtr) and
2624 (pq != Node::NullPtr));
2625 assert((RLINK(pp) == p) or (LLINK(pp) == p));
2626 assert((RLINK(pq) == q) or (LLINK(pq) == q));
2627 assert(RLINK(q) == Node::NullPtr);
2628
2629 /* Set of pp to its new son q */
2630 if (RLINK(pp) == p)
2631 RLINK(pp) = q;
2632 else
2633 LLINK(pp) = q;
2634
2635 RLINK(q) = RLINK(p);
2636 RLINK(p) = Node::NullPtr;
2637
2638 /* Checks if predecessor is left child of p. In this case, p will
2639 become q's son. This situation happens when p's son does not have
2640 a right branch */
2641 if (LLINK(p) == q)
2642 {
2643 LLINK(p) = LLINK(q);
2644 LLINK(q) = p;
2645 pq = pp;
2646 pp = q;
2647 return;
2648 }
2649
2650 /* In this case, predecessor is the rightmost node descending from
2651 right son of p */
2652 Node *ql = LLINK(q);
2653 LLINK(q) = LLINK(p);
2654 RLINK(pq) = p;
2655 LLINK(p) = ql;
2656 std::swap(pp, pq);
2657}
2658
2672template <BinNodeLike Node, class Key = typename Node::key_type,
2674inline Node *insert_root_rec(Node *root, Node *p, const Compare &cmp = Compare()) noexcept
2675{
2677 if (root == Node::NullPtr)
2678 return p; /* insertion in an empty tree */
2679
2680 if (cmp(KEY(p), KEY(root)))
2681 { /* insert in the left subtree */
2682 Node *left_branch = insert_root_rec(LLINK(root), p, cmp);
2683 if (left_branch == Node::NullPtr)
2684 return Node::NullPtr;
2685
2686 LLINK(root) = left_branch;
2688 }
2689 else if (cmp(KEY(root), KEY(p)))
2690 { /* insert in the right subtree */
2691 Node *right_branch = insert_root_rec(RLINK(root), p, cmp);
2692 if (right_branch == Node::NullPtr)
2693 return Node::NullPtr;
2694
2695 RLINK(root) = right_branch;
2697 }
2698 else
2699 return Node::NullPtr; /* duplicated key */
2700
2701 return root;
2702}
2703
2714template <BinNodeLike Node, class Key = typename Node::key_type,
2716inline Node *search_or_insert_root_rec(Node *root, Node *p, const Compare &cmp = Compare()) noexcept
2717{
2719 if (root == Node::NullPtr)
2720 return p; // insertion in empty tree
2721
2722 if (cmp(KEY(p), KEY(root)))
2723 { // insert in left subtree
2724 Node *left_branch = search_or_insert_root_rec(LLINK(root), p, cmp);
2725 if (left_branch == p)
2726 {
2727 LLINK(root) = left_branch;
2729 return p;
2730 }
2731
2732 return left_branch;
2733 }
2734 if (cmp(KEY(root), KEY(p)))
2735 { // insert in right subtree
2736 Node *right_branch = search_or_insert_root_rec(RLINK(root), p, cmp);
2737 if (right_branch == p)
2738 {
2739 RLINK(root) = right_branch;
2741 return p;
2742 }
2743
2744 return right_branch;
2745 }
2746
2747 return root;
2748}
2749
2757template <class Node>
2759{
2760 Node *root = nullptr;
2761 Node *curr = Node::NullPtr;
2762 // Pending nodes. Up to Inline_Depth of them live inside the iterator, so
2763 // iterating a tree that is not deeper never allocates; a deeper tree moves
2764 // them to the heap. The balanced trees fit (AvlNode::MaxHeight is 40 and
2765 // RbNode::MaxHeight 128). The generic BinNode estimates a MaxHeight of
2766 // 2048 for unbalanced trees; keeping all of it inline cost 16 KiB per
2767 // iterator, so the inline part stops at 128.
2768 static constexpr size_t Inline_Depth = Node::MaxHeight < 128 ? Node::MaxHeight : 128;
2770
2771public:
2773 void swap(BinNodePrefixIterator &it) noexcept
2774 {
2775 std::swap(root, it.root);
2776 std::swap(curr, it.curr);
2777 s.swap(it.s);
2778 }
2779
2781
2785 {
2786 // empty
2787 }
2788
2790 {
2791 // empty
2792 }
2793
2795 {
2796 swap(it);
2797 }
2798
2800 void reset_first() noexcept
2801 {
2802 curr = root;
2803 s.empty();
2804 }
2805
2806private:
2807 // Helper function for finding last node
2808 static Node *last(Node *p) noexcept
2809 {
2810 if (RLINK(p) != Node::NullPtr)
2811 return last(RLINK(p));
2812
2813 if (LLINK(p) != Node::NullPtr)
2814 return last(LLINK(p));
2815
2816 return p;
2817 }
2818
2819public:
2821 void reset_last() noexcept
2822 {
2823 s.empty();
2824 if (root == Node::NullPtr)
2825 {
2826 curr = Node::NullPtr;
2827 return;
2828 }
2829
2830 curr = last(root);
2831 }
2832
2834 void end() noexcept
2835 {
2836 curr = Node::NullPtr;
2837 s.empty();
2838 }
2839
2841 {
2842 if (this == &it)
2843 return *this;
2844
2845 root = it.root;
2846 curr = it.curr;
2847 s = it.s;
2848 return *this;
2849 }
2850
2852 {
2853 swap(it);
2854 return *this;
2855 }
2856
2858 [[nodiscard]] bool has_curr() const noexcept
2859 {
2860 return curr != Node::NullPtr;
2861 }
2862
2864 Node *get_curr_ne() const noexcept
2865 {
2866 return curr;
2867 }
2868
2871 {
2872 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
2873 return get_curr_ne();
2874 }
2875
2881 void next_ne()
2882 {
2883 auto l = LLINK(curr), r = RLINK(curr);
2884 if (l != Node::NullPtr)
2885 {
2886 curr = l;
2887 if (r != Node::NullPtr)
2888 s.append(r);
2889 return;
2890 }
2891
2892 if (r != Node::NullPtr)
2893 {
2894 curr = r;
2895 return;
2896 }
2897
2898 if (s.is_empty())
2899 curr = Node::NullPtr;
2900 else
2901 curr = s.remove_last();
2902 }
2903
2905 void next()
2906 {
2907 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
2908 next_ne();
2909 }
2910};
2911
2935template <BinNodeLike Node, class Op>
2937{
2938 for (BinNodePrefixIterator<Node> it(root); it.has_curr(); it.next_ne())
2939 if (not op(it.get_curr()))
2940 return false;
2941 return true;
2942}
2943
2962template <BinNodeLike Node, class Op>
2964{
2965 for (BinNodePrefixIterator<Node> it(root); it.has_curr(); it.next_ne())
2966 op(it.get_curr());
2967}
2968
2976template <class Node>
2978{
2979 mutable Node *root = Node::NullPtr;
2980 Node *curr = Node::NullPtr;
2981 mutable long pos = 0;
2982
2983 // Pending nodes. Up to Inline_Depth of them live inside the iterator, so
2984 // iterating a tree that is not deeper never allocates; a deeper tree moves
2985 // them to the heap. The balanced trees fit (AvlNode::MaxHeight is 40 and
2986 // RbNode::MaxHeight 128). The generic BinNode estimates a MaxHeight of
2987 // 2048 for unbalanced trees; keeping all of it inline cost 16 KiB per
2988 // iterator, so the inline part stops at 128.
2989 static constexpr size_t Inline_Depth = Node::MaxHeight < 128 ? Node::MaxHeight : 128;
2991
2993 {
2994 while (LLINK(r) != Node::NullPtr)
2995 {
2996 s.append(r);
2997 r = LLINK(r);
2998 }
2999 return r;
3000 }
3001
3002 static Node *advance_to_max(Node *r) noexcept
3003 {
3004 while (RLINK(r) != Node::NullPtr)
3005 r = RLINK(r);
3006
3007 return r;
3008 }
3009
3010 void init()
3011 {
3012 if (root != Node::NullPtr)
3014 pos = 0;
3015 }
3016
3017public:
3019 bool is_in_first() const noexcept
3020 {
3021 return curr != Node::NullPtr and LLINK(curr) == Node::NullPtr and s.is_empty();
3022 }
3023
3024 bool is_last() const noexcept
3025 {
3026 return curr != Node::NullPtr and RLINK(curr) == Node::NullPtr and s.is_empty();
3027 }
3028
3029 void swap(BinNodeInfixIterator &it) noexcept
3030 {
3031 std::swap(root, it.root);
3032 std::swap(curr, it.curr);
3033 std::swap(pos, it.pos);
3034 s.swap(it.s);
3035 }
3036
3038
3045 {
3046 init();
3047 }
3048
3050 : root(it.root), curr(it.curr), pos(it.pos), s(it.s)
3051 {
3052 // empty
3053 }
3054
3056 {
3057 swap(it);
3058 }
3059
3063 {
3064 s.empty();
3065 init();
3066 }
3067
3069 void reset_last() noexcept
3070 {
3071 s.empty();
3072 if (root == Node::NullPtr)
3073 {
3074 curr = Node::NullPtr;
3075 pos = 0;
3076 return;
3077 }
3078
3080 pos = -1; // pending: computed lazily by get_pos()
3081 }
3082
3083 void end() noexcept
3084 {
3085 s.empty();
3086 curr = Node::NullPtr;
3087 pos = 0;
3088 }
3089
3091 {
3092 if (this == &it)
3093 return *this;
3094
3095 root = it.root;
3096 curr = it.curr;
3097 pos = it.pos;
3098 s = it.s;
3099 return *this;
3100 }
3101
3103 {
3104 swap(it);
3105 return *this;
3106 }
3107
3109 bool has_curr() const noexcept
3110 {
3111 return curr != Node::NullPtr;
3112 }
3113
3115 Node *get_curr_ne() const noexcept
3116 {
3117 return curr;
3118 }
3119
3122 {
3123 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
3124 return curr;
3125 }
3126
3128 size_t get_pos() const
3129 {
3130 if (pos < 0)
3131 pos = static_cast<long>(size(root)) - 1;
3132 return pos;
3133 }
3134
3137 void next_ne()
3138 {
3139 if (pos < 0) // resolve the position left pending by reset_last()
3140 pos = static_cast<long>(size(root)) - 1;
3141
3142 ++pos;
3143 curr = RLINK(curr);
3144 if (curr != Node::NullPtr)
3145 {
3147 return;
3148 }
3149
3150 if (s.is_empty())
3151 curr = Node::NullPtr;
3152 else
3153 curr = s.remove_last();
3154 }
3155
3158 void next()
3159 {
3160 ah_overflow_error_if(not has_curr()) << "Iterator overflow";
3161 next_ne();
3162 }
3163};
3164
3188template <BinNodeLike Node, class Op>
3190{
3191 for (BinNodeInfixIterator<Node> it(root); it.has_curr(); it.next_ne())
3192 if (not op(it.get_curr()))
3193 return false;
3194 return true;
3195}
3196
3201template <BinNodeLike Node, class Op>
3202bool traverse(Node *root, Op op)
3203{
3204 return infix_traverse(root, op);
3205}
3206
3225template <BinNodeLike Node, class Op>
3227{
3228 for (BinNodeInfixIterator<Node> it(root); it.has_curr(); it.next_ne())
3229 op(it.get_curr());
3230}
3231} // namespace Aleph
3232
3233#endif // TPL_BINNODEUTILS_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#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_runtime_error_if(C)
Throws std::runtime_error if condition holds.
Definition ah-errors.H:415
Standard functor implementations and comparison objects.
WeightedDigraph::Node Node
Space-efficient bit array implementation.
@ KEY
Definition btreepic.C:169
EepicNode< long > * build_tree()
Definition btreepic.C:1434
size_t size_t int32_t * out
Definition ca-c-api.h:120
Inorder iterator on the nodes of a binary tree.
Node * get_curr_ne() const noexcept
Return the current link guaranteeing no exception. Be careful.
void next()
Move the iterator one position forward.
void reset_last() noexcept
Reset the iterator to the last node inorder.
Node * get_curr() const
Return the current node. Throw overflow_error if there is no current.
BinNodeInfixIterator(const BinNodeInfixIterator &it)
bool is_last() const noexcept
bool has_curr() const noexcept
Return true the iterator has current node.
void next_ne()
Move forward without checking the position; it may throw bad_alloc, as the constructor does.
bool is_in_first() const noexcept
Return true if the iterator is on the first node.
SmallVector< Node *, Inline_Depth > s
BinNodeInfixIterator(BinNodeInfixIterator &&it) noexcept
BinNodeInfixIterator & operator=(const BinNodeInfixIterator &it)
static constexpr size_t Inline_Depth
static Node * advance_to_max(Node *r) noexcept
void reset_first()
Reset the iterator to the first node inorder; it may throw bad_alloc, as the constructor does.
size_t get_pos() const
Return the current position of iterator. Only valid if has_curr() == true.
void swap(BinNodeInfixIterator &it) noexcept
BinNodeInfixIterator(Node *r)
Initialize an iterator on the first node inorder.
Preorder iterator on the nodes of a binary tree.
static constexpr size_t Inline_Depth
Node * get_curr_ne() const noexcept
Return the current link guaranteeing no exception. Be careful.
bool has_curr() const noexcept
Return true if iterator has current node.
BinNodePrefixIterator(BinNodePrefixIterator &&it) noexcept
Node * get_curr() const
Return a pointer to current node.
void reset_first() noexcept
Reset the iterator to the first node in preorder sense.
void next_ne()
Move the iterator one position forward without checking it.
void reset_last() noexcept
Reset the iterator to the last node in preorder.
BinNodePrefixIterator(Node *r) noexcept
Initialize an iterator on the first node in preorder for the tree with root r
void next()
Move the iterator one position forward.
void swap(BinNodePrefixIterator &it) noexcept
Swap thiswith it
BinNodePrefixIterator & operator=(const BinNodePrefixIterator &it)
void end() noexcept
Put the iterator in end state.
SmallVector< Node *, Inline_Depth > s
BinNodePrefixIterator(const BinNodePrefixIterator &it)
static Node * last(Node *p) noexcept
Contiguous array of bits.
Definition bitArray.H:201
int read_bit(const size_t i) const
Read bit i.
Definition bitArray.H:409
void load_from_array_of_chars(const unsigned char str[], const size_t num_bits)
Reads an array of bits saved in a character array.
Definition bitArray.H:762
void load(std::istream &input)
Loads an array of bits saved with save().
Definition bitArray.H:661
void push(const unsigned int value)
Inserts the value at the end of the array.
Definition bitArray.H:506
constexpr size_t size() const noexcept
Returns the dimension of the bit array.
Definition bitArray.H:350
Dynamic doubly linked list with O(1) size and bidirectional access.
T & append(const T &item)
Append a copied item at the end of the list.
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.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
Generic inorder traversal of a binary tree.
void traverse(Node *root, Op &&op) const
Invoke to traversal from root node.
static void for_each_inorder(Node *root, Op &&op)
void operator()(Node *root, Op &op) const
See traverse(Node * root, Op && op).
Generic postorder traversal of a binary tree.
void operator()(Node *root, Op &op) const
See traverse(Node * root, Op && op).
static void postorder(Node *root, Op &&op)
void traverse(Node *root, Op &&op) const
Invoke the traversal.
Generic preorder traversal of a binary tree.
static void preorder(Node *root, Op &&op)
void traverse(Node *root, Op &&op) const
Invoke the traversal.
void operator()(Node *root, Op &op) const
See traverse(Node * root, Op && op).
Contiguous dynamic array with N elements of inline storage.
T & push_back(const T &item)
STL-style alias of append(const T &).
T & append(const T &item)
Append a copy of item.
void empty() noexcept
Destroy all elements (Aleph convention).
void swap(SmallVector &v) noexcept(std::is_nothrow_move_constructible_v< T >)
Swap contents with v.
T remove_last()
Remove and return the last element.
bool is_empty() const noexcept
Return true if no elements are stored. O(1).
__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
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
bool prefix_traverse(Node *root, Op op)
Traverse a tree in preorder via its iterator and performs a conditioned operation on each item.
int postOrderRec(Node *root, void(*visitFct)(Node *, int, int))
Traverse recursively in postorder a binary tree.
constexpr bool nothrow_compare_copy_v
Whether Compare compares two keys of type Key without throwing, as nothrow_compare_v,...
Node * rotate_to_left(Node *p) noexcept
Rotate to the left the tree with root p
int preOrderRec(Node *root, void(*visitFct)(Node *, int, int))
Traverse recursively in preorder a binary tree.
void split_key_dup_rec(Node *&root, const typename Node::key_type &key, Node *&ts, Node *&tg, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
Split a tree according to a key value.
void save_tree_in_array_of_chars(Node *root, const std::string &array_name, std::ostream &output)
Generate C++ array declarations for a binary tree.
Node * search_rank_parent(Node *root, const typename Node::key_type &key, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
Rank search of a key in a binary search tree.
bool split_key_rec_helper(Node *root, const typename Node::key_type &key, Node *&ts, Node *&tg, Compare &cmp) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
The recursion of split_key_rec().
void save_tree_keys_in_prefix(Node *root, std::ostream &output)
Store in output stream the tree keys in preorder.
Node * search_parent(Node *root, const typename Node::key_type &key, Node *&parent, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
Search a key and find its node and parent.
bool split_key_rec(Node *&root, const typename Node::key_type &key, Node *&ts, Node *&tg, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
Split recursively according to a key.
void load_tree_keys_in_prefix(Node *root, std::istream &input)
Load the keys stored in preorder from an input stream.
bool level_traverse(Node *root, Operation &operation)
Level traverse a tree and execute an operation.
DynDlist< Node * > compute_nodes_in_level(Node *root, const int &level)
Count the number of nodes in a specific tree level.
Node * join_preorder(Node *t1, Node *t2, Node *&dup, const Compare &cmp=Compare()) noexcept
Union of two binary search trees.
void swap_node_with_successor(Node *p, Node *&pp, Node *q, Node *&pq) noexcept
Swap a node with its successor inorder.
Node * remove_from_bst(Node *&root, const typename Node::key_type &key, const Compare &cmp=Compare()) noexcept
Remove a key from a binary search tree.
void for_each_in_order(Node *root, Op &&op)
Execute an operation in order sense for each node of tree.
Node * find_predecessor(Node *p, Node *&pp) noexcept
Find the inorder predecessor of p
Node * load_tree_from_array(const unsigned char bits[], const size_t &num_bits, const char *keys[])
Build a binary tree from two arrays.
Node * find_min(Node *root) noexcept
Return the minimum key contained in a binary search tree.
bool traverse(Node *root, Op op)
See infix_traverse().
Node * rotate_to_right(Node *p) noexcept
Rotate to the right the tree with root p
Node * find_successor(Node *p, Node *&pp) noexcept
Find the inorder successor of p
Node * copyRec(Node *root)
Copy a tree.
void for_each_postorder(Node *root, Op &&op)
Execute an operation in postorder sense for each node of tree.
Node * load_tree(std::istream &input)
Load and build a binary tree from a stream.
size_t compute_height_bounded(Node *root, const size_t levels) noexcept
Compute the height of a tree by a recursion of bounded depth.
constexpr bool nothrow_condition_v
Whether calling Fct with Args, and taking its result as a bool in either way, cannot throw.
void for_each_preorder(Node *root, Op &&op)
Execute an operation in preorder sense for each node of tree.
Node * search_or_insert_in_bst(Node *&r, Node *p, const Compare &cmp=Compare()) noexcept
Search or insert a node in a binary search tree.
void save_tree(Node *root, std::ostream &output)
Store a binary tree in a stream.
void dispose_tree_by_link_inversion(Node *root, Dispose &dispose) noexcept
Dispose of every node of a tree in postorder with additional memory.
ThreeWayCmp three_way_compare(const T &a, const T &b, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, T >)
Three-way comparison using a binary comparator.
constexpr bool nothrow_compare_keys_v
Whether the calls of Cmp that compare two keys of type Key, constant or not, give a bool without thro...
size_t compute_height_with_stack(Node *root) noexcept
Compute the height of a tree with an explicit stack of pending subtrees.
bool check_bst(Node *p, const Compare &cmp=Compare())
Return true if p is a binary search tree.
constexpr size_t Bin_Tree_Depth_Bound
Depth up to which the traversals below work inside the call stack.
Node * bits_to_tree(const BitArray &array, int idx=0)
Build a binary tree given its bits code.
void split_key_dup_rec_helper(Node *root, const typename Node::key_type &key, Node *&ts, Node *&tg, Compare &cmp) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
The recursion of split_key_dup_rec().
Node * insert_in_bst(Node *&r, Node *p, const Compare &cmp=Compare()) noexcept
Insert a node p in a binary search tree.
void tree_to_bits(Node *root, BitArray &array)
Compute a bit code for the binary tree.
size_t internal_path_length(Node *p) noexcept
Compute the internal path length.
void preOrderThreaded(Node *node, void(*visitFct)(Node *))
Traverse preorder a binary tree without recursion and without stack.
void inOrderThreaded(Node *root, void(*visitFct)(Node *))
Traverse inorder a binary tree without recursion and without stack.
Node * preorder_to_bst(DynArray< typename Node::key_type > &preorder, int l, int r, const Compare &cmp=Compare())
Build a binary search tree from its preorder traversal.
void dispose_tree_nodes(Node *root, Dispose &dispose, const size_t levels=Bin_Tree_Depth_Bound) noexcept
Dispose of every node of a tree in postorder.
void levelOrder(Node *root, void(*visitFct)(Node *, int, bool))
Traverse a binary tree by levels.
int inOrderRec(Node *root, void(*visitFct)(Node *, int, int))
Traverse recursively inorder a binary tree.
Node * join_exclusive(Node *&ts, Node *&tg) noexcept
Exclusive join of two binary trees.
void destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
Node * search_or_insert_root_rec(Node *root, Node *p, const Compare &cmp=Compare()) noexcept
Search and eventually insert p as root in a binary search tree.
Node * searchInBinTree(Node *root, const typename Node::key_type &key, const Compare &cmp=Compare()) noexcept(nothrow_compare_v< Compare, typename Node::key_type >)
Search a key in a binary search tree using optimistic search.
Node * insert_dup_in_bst(Node *&root, Node *p, const Compare &cmp=Compare()) noexcept
Insert a node p in a binary search tree.
Node * insert_root(Node *&root, Node *p, const Compare &cmp=Compare()) noexcept
Insert the node p as root of a binary search tree.
Node * insert_dup_root(Node *&root, Node *p, const Compare &cmp=Compare()) noexcept
Insert node p as root of a binary search tree.
void swap_node_with_predecessor(Node *p, Node *&pp, Node *q, Node *&pq) noexcept
Swap a node with its predecessor inorder.
size_t compute_cardinality_rec(Node *root) noexcept
Count the number of nodes of a binary tree.
Node * insert_root_rec(Node *root, Node *p, const Compare &cmp=Compare()) noexcept
Insert a node as root in a binary search tree.
void assert_valid_tree_root(const Node *root) noexcept
Debug-only check that root is a valid tree for Node.
constexpr bool nothrow_compare_v
Whether Compare compares two keys of type Key without throwing, as the operations of the trees call i...
bool infix_traverse(Node *root, Op op)
Traverse a tree in inorder via its iterator and performs a conditioned operation on each item.
size_t computeHeightRec(Node *root) noexcept
Compute the height of root
Node * find_max(Node *root) noexcept
Return the maximum key contained in a binary search tree.
void split_key(Node *&root, const Key &key, Node *&l, Node *&r, const Compare &cmp=Compare()) noexcept
Split a binary search tree according to a key.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
static void infix(Node *root, DynList< Node * > &acc)
static void suffix(Node *root, DynList< Node * > &acc)
void infix_for_each(Node *root, Op op)
Traverse all the container and performs an operation on each element.
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
void inorder_rec_helper(Node *node, const int &level, int &position, void(*visitFct)(Node *, int, int))
void load_tree_keys_from_array(Node *root, const char *keys[], int &idx)
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
bool areEquivalents(Node *t1, Node *t2, Equal &op) noexcept
Return true if trees are equivalents.
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
void preorder_rec_helper(Node *p, const int &level, int &position, void(*visitFct)(Node *, int, int))
static void prefix(Node *root, DynList< Node * > &acc)
and
Check uniqueness with explicit hash + equality functors.
void postorder_rec_helper(Node *node, const int &level, int &position, void(*visitFct)(Node *, int, int))
bool less_or_equal_than(const T &op1, const T &op2, Compare &cmp)
Determines if op1 is less than or equal to op2 using a comparison operator.
void put_tree_keys_in_array(Node *root, std::ostream &out)
Node< Key > * build_postorder(const DynArray< Key > &post, long lp, long rp, const DynArray< Key > &in, long li, long ri)
ThreeWayCmp
Constants for three-way comparison results.
@ CmpGreater
First argument is greater than second.
@ CmpLess
First argument is less than second.
@ CmpEqual
Arguments are equal.
Node * bits_to_tree_helper(const BitArray &array, int &i)
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
size_t internal_path_length_helper(Node *p, const size_t &level) noexcept
bool areSimilar(Node *t1, Node *t2) noexcept
Return true if both trees are similar.
bool check_bst_range(Node *p, const typename Node::key_type *min_key, const typename Node::key_type *max_key, const Compare &cmp)
void compute_nodes_in_level_helper(Node *root, long level, const long current_level, DynDlist< Node * > &level_list)
void callKeyDestructorsRec(Node *&root) noexcept
Traverses the tree and calls key's destructors.
void prefix_for_each(Node *root, Op op)
Traverse in preorder all the container and performs an operation on each element.
#define RLINK(i, n)
int keys[]
#define LLINK(i, n)
DynArray< int > preorder
DynArray< int > postorder
DynArray< int > inorder
Gsl_Compatible_Rng r
Circular queue implementations backed by arrays.
Stack implementations backed by dynamic or fixed arrays.
Basic binary tree node definitions.
Dynamic doubly linked list implementation.
Dynamic queue implementation based on linked lists.
Dynamic array with inline storage (Aleph::SmallVector).
DynList< int > l
ofstream output
Definition writeHeap.C:215