49#include <gtest/gtest.h>
56using namespace testing;
60 static std::vector<int> * g_visit_acc =
nullptr;
64 if (g_visit_acc !=
nullptr)
65 g_visit_acc->push_back(
KEY(p));
70 std::vector<BinNode<int> *> allocated;
75 allocated.push_back(p);
80 for (
const auto * p : allocated)
88 std::vector<typename Node::key_type>
keys;
89 Aleph::infix_for_each<Node>(
root, [&] (
Node * p) {
keys.push_back(
KEY(p)); });
97 ASSERT_TRUE(std::is_sorted(
keys.begin(),
keys.end()));
100 template <
class Node>
103 if (
root == Node::NullPtr)
112 bool operator()(
BinNode<int> * p,
const char * str)
const
125 return std::to_string(
KEY(p));
131 std::vector<BinNode<int> *> v;
132 for (
auto it =
l.
get_it(); it.has_curr(); it.next_ne())
133 v.push_back(it.get_curr_ne());
139 std::vector<BinNode<int> *> v;
140 for (
auto it =
l.
get_it(); it.has_curr(); it.next_ne())
141 v.push_back(it.get_curr_ne());
147 std::vector<int>
out;
149 for (
auto * p :
nodes)
154 std::vector<unsigned char> parse_uc_array(
const std::string & s,
const std::string & var_name)
156 const std::string needle =
"const unsigned char " + var_name;
157 auto pos = s.find(needle);
158 if (pos == std::string::npos)
161 pos = s.find(
'{', pos);
162 if (pos == std::string::npos)
165 auto end = s.find(
'}', pos);
166 if (end == std::string::npos)
169 std::vector<unsigned char> bytes;
170 std::string inside = s.substr(pos + 1, end - pos - 1);
171 std::stringstream ss(inside);
177 bytes.push_back(
static_cast<unsigned char>(val));
178 while (ss && (ss.peek() ==
',' || std::isspace(ss.peek())))
184 std::vector<std::string> parse_key_array(
const std::string & s,
const std::string & var_name)
186 const std::string needle =
"const char * " + var_name +
"[]";
187 auto pos = s.find(needle);
188 if (pos == std::string::npos)
191 pos = s.find(
'{', pos);
192 if (pos == std::string::npos)
195 auto end = s.find(
"};", pos);
196 if (end == std::string::npos)
199 std::string inside = s.substr(pos + 1, end - pos - 1);
201 std::vector<std::string> storage;
203 while (i < inside.size())
205 while (i < inside.size() &&
206 (std::isspace(
static_cast<unsigned char>(inside[i])) || inside[i] ==
','))
208 if (i >= inside.size())
211 if (inside.compare(i, 7,
"nullptr") == 0)
217 if (inside[i] !=
'"')
222 while (i < inside.size() && inside[i] !=
'"')
224 if (inside[i] ==
'\\' && i + 1 < inside.size())
226 char esc = inside[i + 1];
228 token.push_back(
'\n');
230 token.push_back(
'\t');
232 token.push_back(esc);
236 token.push_back(inside[i++]);
238 if (i >= inside.size())
241 storage.push_back(token);
247TEST(BinNodeUtils, PrefixInfixSuffixLists)
250 auto *
root = pool.make(2);
258 EXPECT_EQ(keys_from_nodes(as_vector(pre_nodes)), (std::vector<int>{2, 1, 3}));
259 EXPECT_EQ(keys_from_nodes(as_vector(
in_nodes)), (std::vector<int>{1, 2, 3}));
260 EXPECT_EQ(keys_from_nodes(as_vector(post_nodes)), (std::vector<int>{1, 3, 2}));
263TEST(BinNodeUtils, ForEachTraversals)
266 auto *
root = pool.make(2);
270 std::vector<int> in, pre, post;
271 Aleph::for_each_in_order<BinNode<int>>(
root, [&] (
BinNode<int> * p) { in.push_back(
KEY(p)); });
272 Aleph::for_each_preorder<BinNode<int>>(
root, [&] (
BinNode<int> * p) { pre.push_back(
KEY(p)); });
273 Aleph::for_each_postorder<BinNode<int>>(
root, [&] (
BinNode<int> * p) { post.push_back(
KEY(p)); });
275 EXPECT_EQ(in, (std::vector<int>{1, 2, 3}));
276 EXPECT_EQ(pre, (std::vector<int>{2, 1, 3}));
277 EXPECT_EQ(post, (std::vector<int>{1, 3, 2}));
280TEST(BinNodeUtils, ComputeNodesInLevel)
283 auto *
root = pool.make(4);
295 EXPECT_EQ(keys_from_nodes(as_vector(l0)), (std::vector<int>{4}));
296 EXPECT_EQ(keys_from_nodes(as_vector(
l1)), (std::vector<int>{2, 6}));
297 EXPECT_EQ(keys_from_nodes(as_vector(
l2)), (std::vector<int>{1, 3, 5, 7}));
300TEST(BinNodeUtils, InternalPathLength)
303 auto *
root = pool.make(2);
310TEST(BinNodeUtils, BuildTreeFromPreorderAndInorder)
313 pre[0] = 4; pre[1] = 2; pre[2] = 1; pre[3] = 3; pre[4] = 6; pre[5] = 5; pre[6] = 7;
315 in[0] = 1; in[1] = 2; in[2] = 3; in[3] = 4; in[4] = 5; in[5] = 6; in[6] = 7;
317 auto *
root = build_tree<BinNode, int>(pre, 0, 6, in, 0, 6);
318 EXPECT_EQ(
inorder(
root), (std::vector<int>{1, 2, 3, 4, 5, 6, 7}));
323TEST(BinNodeUtils, BuildTreeFromPostorderAndInorder)
326 post[0] = 1; post[1] = 3; post[2] = 2; post[3] = 5; post[4] = 7; post[5] = 6; post[6] = 4;
328 in[0] = 1; in[1] = 2; in[2] = 3; in[3] = 4; in[4] = 5; in[5] = 6; in[6] = 7;
330 auto *
root = build_postorder<BinNode, int>(post, 0, 6, in, 0, 6);
331 EXPECT_EQ(
inorder(
root), (std::vector<int>{1, 2, 3, 4, 5, 6, 7}));
336TEST(BinNodeUtils, SaveTreeLoadTreeRoundtrip)
339 auto *
root = pool.make(2);
343 std::stringstream ss;
345 auto * loaded = load_tree<BinNode<int>>(ss);
347 EXPECT_EQ(
inorder(loaded), (std::vector<int>{1, 2, 3}));
352TEST(BinNodeUtils, LoadTreeKeysInPrefixThrowsOnShortInput)
357 std::stringstream ss;
365TEST(BinNodeUtils, SaveTreeInArrayOfCharsLoadTreeFromArrayRoundtrip)
368 auto *
root = pool.make(2);
372 std::ostringstream
out;
373 const std::string name =
"t";
374 save_tree_in_array_of_chars<BinNode<int>, GetIntKey>(
root, name,
out);
376 const std::string gen =
out.str();
378 auto bytes = parse_uc_array(gen, name +
"_cdp");
379 ASSERT_FALSE(bytes.empty());
381 const std::string key_var = name +
"_k";
382 auto storage = parse_key_array(gen, key_var);
383 ASSERT_FALSE(storage.empty());
385 std::vector<const char *>
keys;
386 for (
auto & s : storage)
387 keys.push_back(s.c_str());
388 keys.push_back(
nullptr);
390 auto * rebuilt = load_tree_from_array<BinNode<int>, LoadIntKey>(bytes.data(),
tree_to_bits(
root).size(),
keys.data());
391 EXPECT_EQ(
inorder(rebuilt), (std::vector<int>{1, 2, 3}));
396TEST(BinNodeUtils, SaveTreeInArrayEscapesKeys)
418 std::ostringstream
out;
419 const std::string name =
"s";
420 save_tree_in_array_of_chars<BinNode<std::string>, GetKey>(
root, name,
out);
422 const std::string gen =
out.str();
423 auto bytes = parse_uc_array(gen, name +
"_cdp");
424 ASSERT_FALSE(bytes.empty());
426 auto storage = parse_key_array(gen, name +
"_k");
427 ASSERT_FALSE(storage.empty());
429 std::vector<const char *>
keys;
430 for (
auto & s : storage)
431 keys.push_back(s.c_str());
432 keys.push_back(
nullptr);
434 auto * rebuilt = load_tree_from_array<BinNode<std::string>, LoadKey>(
438 (std::vector<std::string>{
"a\"b",
"root",
"c\\d"}));
444TEST(BinNodeUtils, ThreadedTraversalsDoNotCorruptTree)
447 auto *
root = pool.make(4);
458 std::vector<int> visited_in;
459 g_visit_acc = &visited_in;
461 g_visit_acc =
nullptr;
462 EXPECT_EQ(visited_in, before_in);
464 std::vector<int> visited_pre;
465 g_visit_acc = &visited_pre;
467 g_visit_acc =
nullptr;
468 EXPECT_EQ(visited_pre, (std::vector<int>{4, 2, 1, 3, 6, 5, 7}));
475TEST(BinNodeUtils, InsertInBstRejectsDuplicates)
484 auto * dup = pool.make(2);
487 assert_bst_and_inorder_sorted(
root);
490TEST(BinNodeUtils, InsertDupInBstAllowsDuplicates)
500 EXPECT_EQ(
inorder(
root), (std::vector<int>{2, 2, 2}));
503TEST(BinNodeUtils, CheckBstRejectsGlobalViolation)
506 auto *
root = pool.make(10);
514TEST(BinNodeUtils, SearchOrInsertInBst)
519 auto * p = pool.make(5);
522 auto * q = pool.make(5);
525 EXPECT_EQ(
KEY(got), 5);
527 assert_bst_and_inorder_sorted(
root);
530TEST(BinNodeUtils, RemoveFromBstReturnsDetachedNode)
535 for (
int k : {3, 1, 4, 2})
540 EXPECT_EQ(
KEY(removed), 1);
544 assert_bst_and_inorder_sorted(
root);
547 assert_bst_and_inorder_sorted(
root);
550TEST(BinNodeUtils, JoinExclusiveEmptiesInputs)
556 for (
int k : {1, 2, 3})
558 for (
int k : {4, 5, 6})
561 auto *
out = join_exclusive<BinNode<int>>(a, b);
565 assert_bst_and_inorder_sorted(
out);
566 EXPECT_EQ(
inorder(
out), (std::vector<int>{1, 2, 3, 4, 5, 6}));
569TEST(BinNodeUtils, JoinPreorderStoresDuplicates)
583 assert_bst_and_inorder_sorted(
out);
584 EXPECT_EQ(
inorder(
out), (std::vector<int>{1, 2, 3}));
586 EXPECT_EQ(
inorder(dup), (std::vector<int>{2}));
589TEST(BinNodeUtils, JoinStoresDuplicates)
601 auto *
out =
join(t1, t2, dup);
603 assert_bst_and_inorder_sorted(
out);
604 EXPECT_EQ(
inorder(
out), (std::vector<int>{1, 2, 3}));
606 EXPECT_EQ(
inorder(dup), (std::vector<int>{2}));
609TEST(BinNodeUtils, SplitKeyRecOnlySplitsWhenKeyAbsent)
613 for (
int k : {1, 2, 3, 4, 5})
625 EXPECT_EQ(
inorder(
root), (std::vector<int>{1, 2, 3, 4, 5}));
628TEST(BinNodeUtils, SplitKeyDupRecSplitsAndEmptiesRoot)
632 for (
int k : {1, 2, 3, 4, 5})
641 assert_bst_and_inorder_sorted(
l);
642 assert_bst_and_inorder_sorted(
r);
644 EXPECT_EQ(
inorder(
l), (std::vector<int>{1, 2}));
645 EXPECT_EQ(
inorder(
r), (std::vector<int>{3, 4, 5}));
648TEST(BinNodeUtils, SplitKeyIterativeSplits)
652 for (
int k : {1, 2, 3, 5, 6})
661 assert_bst_and_inorder_sorted(
l);
662 assert_bst_and_inorder_sorted(
r);
664 EXPECT_EQ(
inorder(
l), (std::vector<int>{1, 2, 3}));
665 EXPECT_EQ(
inorder(
r), (std::vector<int>{5, 6}));
668TEST(BinNodeUtils, InfixIteratorTraversesInSortedOrder)
673 for (
int k : {5, 3, 7, 2, 4, 6, 8})
677 std::vector<int> got;
684 EXPECT_EQ(got, (std::vector<int>{2, 3, 4, 5, 6, 7, 8}));
687TEST(BinNodeUtils, IteratorsHandleTreesDeeperThanMaxHeight)
694 std::vector<BinNode<int> *> spine(n);
695 for (
int i = 0; i < n; ++i)
697 spine[i] = pool.make(2 * i);
698 RLINK(spine[i]) = pool.make(2 * i + 1);
700 LLINK(spine[i - 1]) = spine[i];
705 for (
int i = 0; i < n; ++i)
707 for (
int i = n - 1; i >= 0; --i)
710 std::vector<int> got;
712 got.push_back(
KEY(it.get_curr_ne()));
717 for (
int i = n - 1; i >= 0; --i)
725 got.push_back(
KEY(it.get_curr_ne()));
729TEST(BinNodeUtils, RotationsPreserveInorder)
733 auto * p = pool.make(2);
734 LLINK(p) = pool.make(1);
735 RLINK(p) = pool.make(3);
740 EXPECT_EQ(before, after);
744 EXPECT_EQ(before, after2);
751 for (
int k : {5, 3, 7, 2, 4, 6, 8})
758TEST(BinNodeUtils, FindSuccessorAndPredecessor)
762 for (
int k : {5, 3, 7, 2, 4, 6, 8})
771 EXPECT_EQ(
KEY(succ), 6);
780TEST(BinNodeUtils, SearchParentReturnsNodeAndUpdatesParent)
784 for (
int k : {5, 3, 7, 2, 4, 6, 8})
794 EXPECT_EQ(
KEY(got), 4);
796 EXPECT_EQ(
KEY(parent), 3);
799TEST(BinNodeUtils, SearchRankParent)
803 for (
int k : {5, 3, 7, 2, 4, 6, 8})
808 EXPECT_EQ(
KEY(p1), 6);
812 EXPECT_EQ(
KEY(p2), 2);
815TEST(BinNodeUtils, InsertRootRecInsertsAndRotatesToRoot)
819 for (
int k : {2, 1, 3})
822 auto * p = pool.make(4);
828 assert_bst_and_inorder_sorted(
root);
831TEST(BinNodeUtils, InsertRootRecRejectsDuplicate)
835 for (
int k : {2, 1, 3})
839 auto * dup = pool.make(2);
844TEST(BinNodeUtils, InsertRootRequiresKeyAbsent)
848 for (
int k : {2, 1, 3})
851 auto * existing = pool.make(2);
854 auto * fresh = pool.make(4);
857 assert_bst_and_inorder_sorted(
root);
860TEST(BinNodeUtils, InsertDupRootAlwaysInserts)
864 for (
int k : {2, 1, 3})
867 auto * dup = pool.make(2);
869 assert_bst_and_inorder_sorted(
root);
872TEST(BinNodeUtils, RemoveFromBstRespectsComparator)
876 bool operator()(
int a,
int b)
const noexcept {
return a > b; }
881 for (
const int k : {1, 2, 3, 4, 5})
889 EXPECT_EQ(
KEY(removed), 4);
894TEST(BinNodeUtils, TreeToBitsAndBitsToTreeRoundtripShapeAndKeys)
902 auto *
root = pool.make(2);
912 const char *
keys[] = {
"2",
"1",
"3",
nullptr};
914 load_tree_keys_from_array<BinNode<int>, LoadIntKey>(rebuilt,
keys, key_idx);
916 EXPECT_EQ(
inorder(rebuilt), (std::vector<int>{1, 2, 3}));
922TEST(BinNodeUtils, BitsToTreeThrowsOnInvalidBits)
931TEST(BinNodeUtils, PreorderToBstBuildsValidTree)
943 assert_bst_and_inorder_sorted(
root);
944 EXPECT_EQ(
inorder(
root), (std::vector<int>{2, 3, 4, 5, 6, 7, 8}));
949TEST(BinNodeUtils, Property_InsertRemoveRandom_StableInvariants)
954 std::mt19937
rng(12345);
955 std::uniform_int_distribution<int> dist(0, 200);
957 std::set<int> present;
959 for (
int i = 0; i < 200; ++i)
962 auto * p = pool.make(
k);
968 assert_bst_and_inorder_sorted(
root);
970 for (
int i = 0; i < 100; ++i)
976 EXPECT_EQ(
KEY(removed),
k);
979 assert_bst_and_inorder_sorted(
root);
989 static inline long alive = 0;
990 static inline long copies_left = -1;
994 Counted_Key() { ++alive; }
995 Counted_Key(
const int v) :
value(v) { ++alive; }
996 Counted_Key(
const Counted_Key & key) :
value(key.
value)
998 if (copies_left == 0)
999 throw std::runtime_error(
"copy of key");
1000 if (copies_left > 0)
1004 Counted_Key & operator = (
const Counted_Key &) =
default;
1005 ~Counted_Key() { --alive; }
1007 bool operator < (
const Counted_Key & key)
const noexcept
1009 return value < key.value;
1015 BinNode<int> * build_chain(
const int n,
const std::function<
bool(
int)> & goes_left)
1019 for (
int i = 1; i < n; ++i)
1022 (goes_left(i) ?
LLINK(last) :
RLINK(last)) = p;
1031 const std::function<
bool(
int)> & goes_left)
1033 size_t mismatches = 0;
1035 for (
int i = 0; i < n; ++i)
1038 return mismatches +
static_cast<size_t>(n - i);
1041 const bool left = i + 1 < n
and goes_left(i + 1);
1042 const bool right = i + 1 < n
and not goes_left(i + 1);
1054TEST(BinNodeUtils, DegenerateTreesAreMeasuredCopiedAndDestroyedWithoutRecursion)
1056 constexpr int n = 1'000'000;
1057 const std::function<bool(
int)> shapes[] =
1059 [] (int) {
return true; },
1060 [] (int) {
return false; },
1061 [] (
const int i) {
return i % 2 == 0; }
1064 for (
const auto & goes_left : shapes)
1066 auto *
root = build_chain(n, goes_left);
1070 EXPECT_EQ(chain_mismatches(
copy, n, goes_left), 0u);
1071 EXPECT_EQ(chain_mismatches(
root, n, goes_left), 0u);
1084TEST(BinNodeUtils, CombTreeIsTallerThanTheBoundOfTheRecursions)
1086 constexpr int levels = 100'000;
1090 auto * spine =
root;
1091 for (
int i = 0; i < levels; ++i)
1097 spine =
RLINK(spine);
1104 size_t mismatches = 0;
1106 for (
int i = 0; i < levels; ++i)
1109 auto * leaf =
LLINK(p);
1115 EXPECT_EQ(mismatches, 0u);
1124TEST(BinNodeUtils, CopyAndDestroyAccountForEveryNode)
1127 ASSERT_EQ(Counted_Key::alive, 0);
1129 std::mt19937
rng(20261013);
1130 std::vector<int>
keys(63);
1131 for (
size_t i = 0; i <
keys.size(); ++i)
1132 keys[i] =
static_cast<int>(i);
1136 for (
const int k :
keys)
1138 const long nodes =
static_cast<long>(
keys.size());
1139 ASSERT_EQ(Counted_Key::alive,
nodes);
1142 for (
long budget = 0; budget <
nodes; ++budget)
1144 Counted_Key::copies_left = budget;
1145 EXPECT_THROW((
void)
copyRec(
root), std::runtime_error) <<
"budget " << budget;
1146 Counted_Key::copies_left = -1;
1147 EXPECT_EQ(Counted_Key::alive,
nodes) <<
"budget " << budget;
1151 EXPECT_EQ(Counted_Key::alive, 2 *
nodes);
1154 std::vector<int> copied;
1155 infix_for_each<Node>(
copy, [&copied] (
Node * p) { copied.push_back(
KEY(p).
value); });
1156 std::sort(
keys.begin(),
keys.end());
1157 EXPECT_EQ(copied,
keys);
1160 EXPECT_EQ(
copy, Node::NullPtr);
1161 EXPECT_EQ(Counted_Key::alive,
nodes);
1163 EXPECT_EQ(
root, Node::NullPtr);
1164 EXPECT_EQ(Counted_Key::alive, 0);
1169TEST(BinNodeUtils, KeyDestructorsRunOnceOnADegenerateTreeWithoutRecursion)
1172 constexpr int n = 1'000'000;
1173 ASSERT_EQ(Counted_Key::alive, 0);
1175 std::vector<void *> storage;
1178 Node * last =
nullptr;
1179 for (
int i = 0; i < n; ++i)
1181 storage.push_back(::operator
new(
sizeof(
Node)));
1182 auto * p =
new (storage.back())
Node(Counted_Key(i));
1183 if (last ==
nullptr)
1185 else if (i % 3 == 0)
1191 ASSERT_EQ(Counted_Key::alive, n);
1195 EXPECT_EQ(
root, Node::NullPtr);
1196 EXPECT_EQ(Counted_Key::alive, 0);
1197 for (
void * mem : storage)
1198 ::operator
delete(mem);
1207 static inline std::vector<int> destroyed;
1211 Recorded_Key() =
default;
1212 Recorded_Key(
const int v) :
value(v) {}
1213 ~Recorded_Key() { destroyed.push_back(value); }
1216 int key_value(
const int key) {
return key; }
1218 int key_value(
const Recorded_Key & key) {
return key.value; }
1222 template <
class Node>
1223 std::vector<Node *> postorder_nodes(
Node *
root)
1225 std::vector<Node *>
nodes;
1226 std::vector<Node *> pending;
1227 if (
root != Node::NullPtr)
1228 pending.push_back(
root);
1229 while (not pending.empty())
1231 Node * p = pending.back();
1234 if (
LLINK(p) != Node::NullPtr)
1235 pending.push_back(
LLINK(p));
1236 if (
RLINK(p) != Node::NullPtr)
1237 pending.push_back(
RLINK(p));
1243 template <
class Node>
1244 std::vector<int> keys_of(
const std::vector<Node *> &
nodes)
1246 std::vector<int>
keys;
1249 keys.push_back(key_value(
KEY(p)));
1255 template <
class Node>
1256 std::vector<Node *> deep_trees()
1260 const auto chain = [&next_key] (
const int n,
const std::function<bool(
int)> & goes_left,
1263 auto *
root =
new Node(next_key++);
1265 for (
int i = 1; i < n; ++i)
1267 auto * p =
new Node(next_key++);
1268 (goes_left(i) ?
LLINK(last) :
RLINK(last)) = p;
1273 const auto left = [] (int) {
return true; };
1274 const auto right = [] (int) {
return false; };
1275 const auto zigzag = [] (
const int i) {
return i % 2 == 0; };
1277 std::vector<Node *> trees;
1278 Node * last =
nullptr;
1279 trees.push_back(
chain(depth, left, last));
1280 trees.push_back(
chain(depth, right, last));
1281 trees.push_back(
chain(depth, zigzag, last));
1284 for (
const bool leaves_on_left : {
true,
false})
1286 auto *
root =
new Node(next_key++);
1287 auto * spine =
root;
1288 for (
int i = 0; i < depth; ++i)
1290 auto * leaf =
new Node(next_key++);
1291 auto * below =
new Node(next_key++);
1292 LLINK(spine) = leaves_on_left ? leaf : below;
1293 RLINK(spine) = leaves_on_left ? below : leaf;
1296 trees.push_back(
root);
1300 std::mt19937
rng(20261013);
1301 for (
const auto & goes_left : {std::function<bool(int)>(left),
1302 std::function<bool(int)>(right),
1303 std::function<bool(int)>(zigzag)})
1305 auto *
root =
chain(depth, goes_left, last);
1306 std::vector<Node *> open = {last};
1307 for (
int i = 0; i < 2000; ++i)
1309 const size_t at = std::uniform_int_distribution<size_t>(0, open.size() - 1)(
rng);
1310 Node * parent = open[at];
1311 auto * p =
new Node(next_key++);
1312 const bool free_left =
LLINK(parent) == Node::NullPtr;
1313 const bool free_right =
RLINK(parent) == Node::NullPtr;
1314 const bool on_left = free_left
and (not free_right or
rng() % 2 == 0);
1315 (on_left ?
LLINK(parent) :
RLINK(parent)) = p;
1316 if (
LLINK(parent) != Node::NullPtr
and RLINK(parent) != Node::NullPtr)
1318 open[at] = open.back();
1323 trees.push_back(
root);
1333TEST(BinNodeUtils, NodesAreDisposedInPostorderWithClearedLinksWhateverTheDepth)
1339 const auto trees = deep_trees<Node>();
1340 for (
size_t t = 0; t < trees.size(); ++t)
1342 const auto nodes = postorder_nodes(trees[t]);
1345 std::vector<int> disposed;
1346 size_t with_links = 0;
1347 const auto dispose = [&] (
Node * p)
noexcept
1349 if (
LLINK(p) != Node::NullPtr or
RLINK(p) != Node::NullPtr)
1351 disposed.push_back(
KEY(p));
1355 EXPECT_EQ(disposed,
expected) <<
"tree " << t <<
", levels " << levels;
1356 EXPECT_EQ(with_links, 0u) <<
"tree " << t <<
", levels " << levels;
1363 const auto trees = deep_trees<Node>();
1364 for (
size_t t = 0; t < trees.size(); ++t)
1366 const auto nodes = postorder_nodes(trees[t]);
1367 std::vector<int> disposed;
1368 const auto dispose = [&disposed] (
Node * p)
noexcept { disposed.push_back(
KEY(p)); };
1370 EXPECT_EQ(disposed, keys_of(
nodes)) <<
"tree " << t;
1376 const auto count = [&calls] (
Node *)
noexcept { ++calls; };
1379 EXPECT_EQ(calls, 0u);
1382TEST(BinNodeUtils, DestroyRecFreesTheNodesInPostorderWhateverTheDepth)
1386 auto trees = deep_trees<Node>();
1387 for (
size_t t = 0; t < trees.size(); ++t)
1389 const auto expected = keys_of(postorder_nodes(trees[t]));
1390 Recorded_Key::destroyed.clear();
1392 EXPECT_EQ(trees[t], Node::NullPtr);
1393 EXPECT_EQ(Recorded_Key::destroyed,
expected) <<
"tree " << t;
1395 Recorded_Key::destroyed.clear();
1400TEST(BinNodeUtils, KeyDestructorsRunInPostorderAndLeaveTheLinksCleared)
1404 auto trees = deep_trees<Node>();
1405 for (
size_t t = 0; t < trees.size(); ++t)
1407 const auto nodes = postorder_nodes(trees[t]);
1409 Recorded_Key::destroyed.clear();
1411 EXPECT_EQ(trees[t], Node::NullPtr);
1412 EXPECT_EQ(Recorded_Key::destroyed,
expected) <<
"tree " << t;
1414 size_t with_links = 0;
1417 if (
LLINK(p) != Node::NullPtr or
RLINK(p) != Node::NullPtr)
1419 ::operator
delete(p);
1421 EXPECT_EQ(with_links, 0u) <<
"tree " << t;
1423 Recorded_Key::destroyed.clear();
bool operator<(const Time &l, const Time &r)
WeightedDigraph::Node Node
size_t size_t int32_t value
size_t size_t int32_t * out
Inorder iterator on the nodes of a binary tree.
Node * get_curr_ne() const noexcept
Return the current link guaranteeing no exception. Be careful.
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.
Preorder iterator on the nodes of a binary tree.
Node for binary search tree.
Contiguous array of bits.
Dynamic doubly linked list with O(1) size and bidirectional access.
Doubly-linked list (defined in tpl_dynList.H).
Minimal std::expected-style result type for C++20.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
static Tree_Node< int > * chain(size_t n)
__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)
void delete_tree(Tree_Node< T > *node)
DynArray< Graph::Node * > nodes
DynList< typename GT::Node * > in_nodes(typename GT::Node *p, SA sa=SA())
Return the nodes connected to the filtered incoming arcs to p.
Node * rotate_to_left(Node *p) noexcept
Rotate to the left the tree with root p
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.
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.
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.
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.
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.
Node * find_predecessor(Node *p, Node *&pp) noexcept
Find the inorder predecessor of p
Node * find_min(Node *root) noexcept
Return the minimum key contained in a binary search tree.
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.
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.
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.
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.
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 destroyRec(Node *&root) noexcept
Free all the memory occupied by the tree root
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.
Node * insert_root_rec(Node *root, Node *p, const Compare &cmp=Compare()) noexcept
Insert a node as root in a binary search tree.
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.
Freq_Node * pred
Predecessor node in level-order traversal.
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)
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
static void prefix(Node *root, DynList< Node * > &acc)
and
Check uniqueness with explicit hash + equality functors.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
bool areSimilar(Node *t1, Node *t2) noexcept
Return true if both trees are similar.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
void callKeyDestructorsRec(Node *&root) noexcept
Traverses the tree and calls key's destructors.
Utility functions for binary tree operations.
Basic binary tree node definitions.
Lazy and scalable dynamic array implementation.