Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
bin-node-utils.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
38#include <algorithm>
39#include <cctype>
40#include <functional>
41#include <new>
42#include <random>
43#include <sstream>
44#include <set>
45#include <stdexcept>
46#include <string>
47#include <vector>
48
49#include <gtest/gtest.h>
50
51#include <tpl_binNode.H>
52#include <tpl_binNodeUtils.H>
53#include <tpl_dynArray.H>
54
55using namespace Aleph;
56using namespace testing;
57
58namespace
59{
60 static std::vector<int> * g_visit_acc = nullptr;
61
62 static void visit_push_key(BinNode<int> * p)
63 {
64 if (g_visit_acc != nullptr)
65 g_visit_acc->push_back(KEY(p));
66 }
67
68 struct NodePool
69 {
70 std::vector<BinNode<int> *> allocated;
71
72 BinNode<int> * make(int k)
73 {
74 auto * p = new BinNode<int>(k);
75 allocated.push_back(p);
76 return p;
77 }
78 ~NodePool()
79 {
80 for (const auto * p : allocated)
81 delete p;
82 }
83 };
84
85 template <class Node>
86 std::vector<typename Node::key_type> inorder(Node * root)
87 {
88 std::vector<typename Node::key_type> keys;
89 Aleph::infix_for_each<Node>(root, [&] (Node * p) { keys.push_back(KEY(p)); });
90 return keys;
91 }
92
93 void assert_bst_and_inorder_sorted(BinNode<int> * root)
94 {
95 ASSERT_TRUE((check_bst<BinNode<int>>(root)));
96 auto keys = inorder(root);
97 ASSERT_TRUE(std::is_sorted(keys.begin(), keys.end()));
98 }
99
100 template <class Node>
101 void delete_tree(Node * root) noexcept
102 {
103 if (root == Node::NullPtr)
104 return;
107 delete root;
108 }
109
110 struct LoadIntKey
111 {
112 bool operator()(BinNode<int> * p, const char * str) const
113 {
114 if (str == nullptr)
115 return false;
116 p->get_key() = std::stoi(str);
117 return true;
118 }
119 };
120
121 struct GetIntKey
122 {
123 std::string operator()(BinNode<int> * p) const
124 {
125 return std::to_string(KEY(p));
126 }
127 };
128
129 std::vector<BinNode<int> *> as_vector(const DynList<BinNode<int> *> & l)
130 {
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());
134 return v;
135 }
136
137 std::vector<BinNode<int> *> as_vector(const DynDlist<BinNode<int> *> & l)
138 {
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());
142 return v;
143 }
144
145 std::vector<int> keys_from_nodes(const std::vector<BinNode<int> *> & nodes)
146 {
147 std::vector<int> out;
148 out.reserve(nodes.size());
149 for (auto * p : nodes)
150 out.push_back(KEY(p));
151 return out;
152 }
153
154 std::vector<unsigned char> parse_uc_array(const std::string & s, const std::string & var_name)
155 {
156 const std::string needle = "const unsigned char " + var_name;
157 auto pos = s.find(needle);
158 if (pos == std::string::npos)
159 return {};
160
161 pos = s.find('{', pos);
162 if (pos == std::string::npos)
163 return {};
164
165 auto end = s.find('}', pos);
166 if (end == std::string::npos)
167 return {};
168
169 std::vector<unsigned char> bytes;
170 std::string inside = s.substr(pos + 1, end - pos - 1);
171 std::stringstream ss(inside);
172 while (ss)
173 {
174 int val;
175 if (!(ss >> val))
176 break;
177 bytes.push_back(static_cast<unsigned char>(val));
178 while (ss && (ss.peek() == ',' || std::isspace(ss.peek())))
179 ss.get();
180 }
181 return bytes;
182 }
183
184 std::vector<std::string> parse_key_array(const std::string & s, const std::string & var_name)
185 {
186 const std::string needle = "const char * " + var_name + "[]";
187 auto pos = s.find(needle);
188 if (pos == std::string::npos)
189 return {};
190
191 pos = s.find('{', pos);
192 if (pos == std::string::npos)
193 return {};
194
195 auto end = s.find("};", pos);
196 if (end == std::string::npos)
197 return {};
198
199 std::string inside = s.substr(pos + 1, end - pos - 1);
200
201 std::vector<std::string> storage;
202 size_t i = 0;
203 while (i < inside.size())
204 {
205 while (i < inside.size() &&
206 (std::isspace(static_cast<unsigned char>(inside[i])) || inside[i] == ','))
207 ++i;
208 if (i >= inside.size())
209 break;
210
211 if (inside.compare(i, 7, "nullptr") == 0)
212 {
213 i += 7;
214 break;
215 }
216
217 if (inside[i] != '"')
218 break;
219 ++i;
220
221 std::string token;
222 while (i < inside.size() && inside[i] != '"')
223 {
224 if (inside[i] == '\\' && i + 1 < inside.size())
225 {
226 char esc = inside[i + 1];
227 if (esc == 'n')
228 token.push_back('\n');
229 else if (esc == 't')
230 token.push_back('\t');
231 else
232 token.push_back(esc);
233 i += 2;
234 continue;
235 }
236 token.push_back(inside[i++]);
237 }
238 if (i >= inside.size())
239 break;
240 ++i;
241 storage.push_back(token);
242 }
243 return storage;
244 }
245}
246
247TEST(BinNodeUtils, PrefixInfixSuffixLists)
248{
249 NodePool pool;
250 auto * root = pool.make(2);
251 LLINK(root) = pool.make(1);
252 RLINK(root) = pool.make(3);
253
254 auto pre_nodes = Aleph::prefix(root);
255 auto in_nodes = Aleph::infix(root);
256 auto post_nodes = Aleph::suffix(root);
257
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}));
261}
262
263TEST(BinNodeUtils, ForEachTraversals)
264{
265 NodePool pool;
266 auto * root = pool.make(2);
267 LLINK(root) = pool.make(1);
268 RLINK(root) = pool.make(3);
269
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)); });
274
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}));
278}
279
280TEST(BinNodeUtils, ComputeNodesInLevel)
281{
282 NodePool pool;
283 auto * root = pool.make(4);
284 LLINK(root) = pool.make(2);
285 RLINK(root) = pool.make(6);
286 LLINK(LLINK(root)) = pool.make(1);
287 RLINK(LLINK(root)) = pool.make(3);
288 LLINK(RLINK(root)) = pool.make(5);
289 RLINK(RLINK(root)) = pool.make(7);
290
291 auto l0 = compute_nodes_in_level(root, 0);
292 auto l1 = compute_nodes_in_level(root, 1);
293 auto l2 = compute_nodes_in_level(root, 2);
294
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}));
298}
299
300TEST(BinNodeUtils, InternalPathLength)
301{
302 NodePool pool;
303 auto * root = pool.make(2);
304 LLINK(root) = pool.make(1);
305 RLINK(root) = pool.make(3);
306
307 EXPECT_EQ(internal_path_length(root), 0u + 1u + 1u);
308}
309
310TEST(BinNodeUtils, BuildTreeFromPreorderAndInorder)
311{
312 DynArray<int> pre(7);
313 pre[0] = 4; pre[1] = 2; pre[2] = 1; pre[3] = 3; pre[4] = 6; pre[5] = 5; pre[6] = 7;
314 DynArray<int> in(7);
315 in[0] = 1; in[1] = 2; in[2] = 3; in[3] = 4; in[4] = 5; in[5] = 6; in[6] = 7;
316
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}));
319 EXPECT_TRUE(check_bst<BinNode<int>>(root));
321}
322
323TEST(BinNodeUtils, BuildTreeFromPostorderAndInorder)
324{
325 DynArray<int> post(7);
326 post[0] = 1; post[1] = 3; post[2] = 2; post[3] = 5; post[4] = 7; post[5] = 6; post[6] = 4;
327 DynArray<int> in(7);
328 in[0] = 1; in[1] = 2; in[2] = 3; in[3] = 4; in[4] = 5; in[5] = 6; in[6] = 7;
329
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}));
332 EXPECT_TRUE(check_bst<BinNode<int>>(root));
334}
335
336TEST(BinNodeUtils, SaveTreeLoadTreeRoundtrip)
337{
338 NodePool pool;
339 auto * root = pool.make(2);
340 LLINK(root) = pool.make(1);
341 RLINK(root) = pool.make(3);
342
343 std::stringstream ss;
344 save_tree(root, ss);
345 auto * loaded = load_tree<BinNode<int>>(ss);
346
347 EXPECT_EQ(inorder(loaded), (std::vector<int>{1, 2, 3}));
348 EXPECT_TRUE(check_bst<BinNode<int>>(loaded));
349 delete_tree(loaded);
350}
351
352TEST(BinNodeUtils, LoadTreeKeysInPrefixThrowsOnShortInput)
353{
354 auto * root = new BinNode<int>(0);
355 LLINK(root) = new BinNode<int>(0);
356
357 std::stringstream ss;
358 ss << 1;
359
360 EXPECT_THROW(load_tree_keys_in_prefix(root, ss), std::runtime_error);
361
363}
364
365TEST(BinNodeUtils, SaveTreeInArrayOfCharsLoadTreeFromArrayRoundtrip)
366{
367 NodePool pool;
368 auto * root = pool.make(2);
369 LLINK(root) = pool.make(1);
370 RLINK(root) = pool.make(3);
371
372 std::ostringstream out;
373 const std::string name = "t";
374 save_tree_in_array_of_chars<BinNode<int>, GetIntKey>(root, name, out);
375
376 const std::string gen = out.str();
377
378 auto bytes = parse_uc_array(gen, name + "_cdp");
379 ASSERT_FALSE(bytes.empty());
380
381 const std::string key_var = name + "_k";
382 auto storage = parse_key_array(gen, key_var);
383 ASSERT_FALSE(storage.empty());
384
385 std::vector<const char *> keys;
386 for (auto & s : storage)
387 keys.push_back(s.c_str());
388 keys.push_back(nullptr);
389
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}));
392 EXPECT_TRUE(check_bst<BinNode<int>>(rebuilt));
393 delete_tree(rebuilt);
394}
395
396TEST(BinNodeUtils, SaveTreeInArrayEscapesKeys)
397{
398 auto * root = new BinNode<std::string>("root");
399 LLINK(root) = new BinNode<std::string>("a\"b");
400 RLINK(root) = new BinNode<std::string>("c\\d");
401
402 struct GetKey
403 {
404 std::string operator()(BinNode<std::string> * p) const { return KEY(p); }
405 };
406
407 struct LoadKey
408 {
409 bool operator()(BinNode<std::string> * p, const char * str) const
410 {
411 if (str == nullptr)
412 return false;
413 p->get_key() = str;
414 return true;
415 }
416 };
417
418 std::ostringstream out;
419 const std::string name = "s";
420 save_tree_in_array_of_chars<BinNode<std::string>, GetKey>(root, name, out);
421
422 const std::string gen = out.str();
423 auto bytes = parse_uc_array(gen, name + "_cdp");
424 ASSERT_FALSE(bytes.empty());
425
426 auto storage = parse_key_array(gen, name + "_k");
427 ASSERT_FALSE(storage.empty());
428
429 std::vector<const char *> keys;
430 for (auto & s : storage)
431 keys.push_back(s.c_str());
432 keys.push_back(nullptr);
433
434 auto * rebuilt = load_tree_from_array<BinNode<std::string>, LoadKey>(
435 bytes.data(), tree_to_bits(root).size(), keys.data());
436
437 EXPECT_EQ(inorder(rebuilt),
438 (std::vector<std::string>{"a\"b", "root", "c\\d"}));
439
441 delete_tree(rebuilt);
442}
443
444TEST(BinNodeUtils, ThreadedTraversalsDoNotCorruptTree)
445{
446 NodePool pool;
447 auto * root = pool.make(4);
448 LLINK(root) = pool.make(2);
449 RLINK(root) = pool.make(6);
450 LLINK(LLINK(root)) = pool.make(1);
451 RLINK(LLINK(root)) = pool.make(3);
452 LLINK(RLINK(root)) = pool.make(5);
453 RLINK(RLINK(root)) = pool.make(7);
454
455 auto before_bits = tree_to_bits(root);
456 auto before_in = inorder(root);
457
458 std::vector<int> visited_in;
459 g_visit_acc = &visited_in;
460 inOrderThreaded(root, &visit_push_key);
461 g_visit_acc = nullptr;
462 EXPECT_EQ(visited_in, before_in);
463
464 std::vector<int> visited_pre;
465 g_visit_acc = &visited_pre;
466 preOrderThreaded(root, &visit_push_key);
467 g_visit_acc = nullptr;
468 EXPECT_EQ(visited_pre, (std::vector<int>{4, 2, 1, 3, 6, 5, 7}));
469
470 EXPECT_EQ(inorder(root), before_in);
471 EXPECT_EQ(tree_to_bits(root).size(), before_bits.size());
472 EXPECT_TRUE(check_bst<BinNode<int>>(root));
473}
474
475TEST(BinNodeUtils, InsertInBstRejectsDuplicates)
476{
477 NodePool pool;
479
480 ASSERT_NE(insert_in_bst(root, pool.make(2)), BinNode<int>::NullPtr);
481 ASSERT_NE(insert_in_bst(root, pool.make(1)), BinNode<int>::NullPtr);
482 ASSERT_NE(insert_in_bst(root, pool.make(3)), BinNode<int>::NullPtr);
483
484 auto * dup = pool.make(2);
485 EXPECT_EQ(insert_in_bst(root, dup), BinNode<int>::NullPtr);
486
487 assert_bst_and_inorder_sorted(root);
488}
489
490TEST(BinNodeUtils, InsertDupInBstAllowsDuplicates)
491{
492 NodePool pool;
494
495 ASSERT_NE(insert_dup_in_bst(root, pool.make(2)), BinNode<int>::NullPtr);
496 ASSERT_NE(insert_dup_in_bst(root, pool.make(2)), BinNode<int>::NullPtr);
497 ASSERT_NE(insert_dup_in_bst(root, pool.make(2)), BinNode<int>::NullPtr);
498
499 EXPECT_TRUE(check_bst<BinNode<int>>(root));
500 EXPECT_EQ(inorder(root), (std::vector<int>{2, 2, 2}));
501}
502
503TEST(BinNodeUtils, CheckBstRejectsGlobalViolation)
504{
505 NodePool pool;
506 auto * root = pool.make(10);
507 LLINK(root) = pool.make(5);
508 RLINK(root) = pool.make(15);
509 RLINK(LLINK(root)) = pool.make(12);
510
511 EXPECT_FALSE(check_bst<BinNode<int>>(root));
512}
513
514TEST(BinNodeUtils, SearchOrInsertInBst)
515{
516 NodePool pool;
518
519 auto * p = pool.make(5);
520 EXPECT_EQ(search_or_insert_in_bst(root, p), p);
521
522 auto * q = pool.make(5);
523 auto * got = search_or_insert_in_bst(root, q);
524 EXPECT_NE(got, q);
525 EXPECT_EQ(KEY(got), 5);
526
527 assert_bst_and_inorder_sorted(root);
528}
529
530TEST(BinNodeUtils, RemoveFromBstReturnsDetachedNode)
531{
532 NodePool pool;
534
535 for (int k : {3, 1, 4, 2})
536 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
537
538 auto * removed = remove_from_bst(root, 1);
539 ASSERT_NE(removed, BinNode<int>::NullPtr);
540 EXPECT_EQ(KEY(removed), 1);
541 EXPECT_EQ(LLINK(removed), BinNode<int>::NullPtr);
542 EXPECT_EQ(RLINK(removed), BinNode<int>::NullPtr);
543
544 assert_bst_and_inorder_sorted(root);
545
546 ASSERT_NE(insert_in_bst(root, removed), BinNode<int>::NullPtr);
547 assert_bst_and_inorder_sorted(root);
548}
549
550TEST(BinNodeUtils, JoinExclusiveEmptiesInputs)
551{
552 NodePool pool;
555
556 for (int k : {1, 2, 3})
557 ASSERT_NE(insert_in_bst(a, pool.make(k)), BinNode<int>::NullPtr);
558 for (int k : {4, 5, 6})
559 ASSERT_NE(insert_in_bst(b, pool.make(k)), BinNode<int>::NullPtr);
560
561 auto * out = join_exclusive<BinNode<int>>(a, b);
562 EXPECT_EQ(a, BinNode<int>::NullPtr);
563 EXPECT_EQ(b, BinNode<int>::NullPtr);
564
565 assert_bst_and_inorder_sorted(out);
566 EXPECT_EQ(inorder(out), (std::vector<int>{1, 2, 3, 4, 5, 6}));
567}
568
569TEST(BinNodeUtils, JoinPreorderStoresDuplicates)
570{
571 NodePool pool;
574
575 for (int k : {1, 2})
576 ASSERT_NE(insert_in_bst(t1, pool.make(k)), BinNode<int>::NullPtr);
577 for (int k : {2, 3})
578 ASSERT_NE(insert_in_bst(t2, pool.make(k)), BinNode<int>::NullPtr);
579
581 auto * out = join_preorder(t1, t2, dup);
582
583 assert_bst_and_inorder_sorted(out);
584 EXPECT_EQ(inorder(out), (std::vector<int>{1, 2, 3}));
585 ASSERT_NE(dup, BinNode<int>::NullPtr);
586 EXPECT_EQ(inorder(dup), (std::vector<int>{2}));
587}
588
589TEST(BinNodeUtils, JoinStoresDuplicates)
590{
591 NodePool pool;
594
595 for (int k : {2, 1})
596 ASSERT_NE(insert_in_bst(t1, pool.make(k)), BinNode<int>::NullPtr);
597 for (int k : {2, 3})
598 ASSERT_NE(insert_in_bst(t2, pool.make(k)), BinNode<int>::NullPtr);
599
601 auto * out = join(t1, t2, dup);
602
603 assert_bst_and_inorder_sorted(out);
604 EXPECT_EQ(inorder(out), (std::vector<int>{1, 2, 3}));
605 ASSERT_NE(dup, BinNode<int>::NullPtr);
606 EXPECT_EQ(inorder(dup), (std::vector<int>{2}));
607}
608
609TEST(BinNodeUtils, SplitKeyRecOnlySplitsWhenKeyAbsent)
610{
611 NodePool pool;
613 for (int k : {1, 2, 3, 4, 5})
614 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
615
618
619 EXPECT_FALSE(split_key_rec(root, 3, l, r));
620 EXPECT_NE(root, BinNode<int>::NullPtr);
621 EXPECT_EQ(l, BinNode<int>::NullPtr);
622 EXPECT_EQ(r, BinNode<int>::NullPtr);
623
624 EXPECT_TRUE(check_bst<BinNode<int>>(root));
625 EXPECT_EQ(inorder(root), (std::vector<int>{1, 2, 3, 4, 5}));
626}
627
628TEST(BinNodeUtils, SplitKeyDupRecSplitsAndEmptiesRoot)
629{
630 NodePool pool;
632 for (int k : {1, 2, 3, 4, 5})
633 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
634
637
639 EXPECT_EQ(root, BinNode<int>::NullPtr);
640
641 assert_bst_and_inorder_sorted(l);
642 assert_bst_and_inorder_sorted(r);
643
644 EXPECT_EQ(inorder(l), (std::vector<int>{1, 2}));
645 EXPECT_EQ(inorder(r), (std::vector<int>{3, 4, 5}));
646}
647
648TEST(BinNodeUtils, SplitKeyIterativeSplits)
649{
650 NodePool pool;
652 for (int k : {1, 2, 3, 5, 6})
653 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
654
657
658 split_key(root, 4, l, r);
659 EXPECT_EQ(root, BinNode<int>::NullPtr);
660
661 assert_bst_and_inorder_sorted(l);
662 assert_bst_and_inorder_sorted(r);
663
664 EXPECT_EQ(inorder(l), (std::vector<int>{1, 2, 3}));
665 EXPECT_EQ(inorder(r), (std::vector<int>{5, 6}));
666}
667
668TEST(BinNodeUtils, InfixIteratorTraversesInSortedOrder)
669{
670 NodePool pool;
672
673 for (int k : {5, 3, 7, 2, 4, 6, 8})
674 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
675
677 std::vector<int> got;
678 while (it.has_curr())
679 {
680 got.push_back(KEY(it.get_curr_ne()));
681 it.next_ne();
682 }
683
684 EXPECT_EQ(got, (std::vector<int>{2, 3, 4, 5, 6, 7, 8}));
685}
686
687TEST(BinNodeUtils, IteratorsHandleTreesDeeperThanMaxHeight)
688{
689 // MaxHeight is only an estimate: an unbalanced tree can be deeper. Build a
690 // left spine s_0 ... s_{n-1}, deeper than MaxHeight, where each s_i also has
691 // a right leaf r_i. Key of s_i is 2 i and key of r_i is 2 i + 1.
692 const int n = 2 * static_cast<int>(BinNode<int>::MaxHeight) + 1;
693 NodePool pool;
694 std::vector<BinNode<int> *> spine(n);
695 for (int i = 0; i < n; ++i)
696 {
697 spine[i] = pool.make(2 * i);
698 RLINK(spine[i]) = pool.make(2 * i + 1);
699 if (i > 0)
700 LLINK(spine[i - 1]) = spine[i];
701 }
702
703 // Preorder: s_0 ... s_{n-1}, then r_{n-1} ... r_0
704 std::vector<int> expected;
705 for (int i = 0; i < n; ++i)
706 expected.push_back(2 * i);
707 for (int i = n - 1; i >= 0; --i)
708 expected.push_back(2 * i + 1);
709
710 std::vector<int> got;
711 for (BinNodePrefixIterator<BinNode<int>> it(spine[0]); it.has_curr(); it.next_ne())
712 got.push_back(KEY(it.get_curr_ne()));
713 EXPECT_EQ(got, expected);
714
715 // Inorder: s_{n-1}, r_{n-1}, s_{n-2}, r_{n-2}, ..., s_0, r_0
716 expected.clear();
717 for (int i = n - 1; i >= 0; --i)
718 {
719 expected.push_back(2 * i);
720 expected.push_back(2 * i + 1);
721 }
722
723 got.clear();
724 for (BinNodeInfixIterator<BinNode<int>> it(spine[0]); it.has_curr(); it.next_ne())
725 got.push_back(KEY(it.get_curr_ne()));
726 EXPECT_EQ(got, expected);
727}
728
729TEST(BinNodeUtils, RotationsPreserveInorder)
730{
731 NodePool pool;
732
733 auto * p = pool.make(2);
734 LLINK(p) = pool.make(1);
735 RLINK(p) = pool.make(3);
736
737 auto before = inorder(p);
738 auto * q = rotate_to_right(p);
739 auto after = inorder(q);
740 EXPECT_EQ(before, after);
741
742 auto * r = rotate_to_left(q);
743 auto after2 = inorder(r);
744 EXPECT_EQ(before, after2);
745}
746
747TEST(BinNodeUtils, FindMinMax)
748{
749 NodePool pool;
751 for (int k : {5, 3, 7, 2, 4, 6, 8})
752 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
753
754 EXPECT_EQ(KEY(find_min(root)), 2);
755 EXPECT_EQ(KEY(find_max(root)), 8);
756}
757
758TEST(BinNodeUtils, FindSuccessorAndPredecessor)
759{
760 NodePool pool;
762 for (int k : {5, 3, 7, 2, 4, 6, 8})
763 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
764
765 auto * p = searchInBinTree(root, 5);
766 ASSERT_NE(p, BinNode<int>::NullPtr);
767
769 auto * succ = find_successor(p, parent);
770 ASSERT_NE(succ, BinNode<int>::NullPtr);
771 EXPECT_EQ(KEY(succ), 6);
772
773 auto * q = searchInBinTree(root, 5);
775 auto * pred = find_predecessor(q, parent2);
776 ASSERT_NE(pred, BinNode<int>::NullPtr);
777 EXPECT_EQ(KEY(pred), 4);
778}
779
780TEST(BinNodeUtils, SearchParentReturnsNodeAndUpdatesParent)
781{
782 NodePool pool;
784 for (int k : {5, 3, 7, 2, 4, 6, 8})
785 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
786
787 BinNode<int> head;
788 head.reset();
789 RLINK(&head) = root;
790
791 BinNode<int> * parent = &head;
792 auto * got = search_parent(root, 4, parent);
793 ASSERT_NE(got, BinNode<int>::NullPtr);
794 EXPECT_EQ(KEY(got), 4);
795 EXPECT_NE(parent, BinNode<int>::NullPtr);
796 EXPECT_EQ(KEY(parent), 3);
797}
798
799TEST(BinNodeUtils, SearchRankParent)
800{
801 NodePool pool;
803 for (int k : {5, 3, 7, 2, 4, 6, 8})
804 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
805
806 auto * p1 = search_rank_parent(root, 6);
807 ASSERT_NE(p1, BinNode<int>::NullPtr);
808 EXPECT_EQ(KEY(p1), 6);
809
810 auto * p2 = search_rank_parent(root, 1);
811 ASSERT_NE(p2, BinNode<int>::NullPtr);
812 EXPECT_EQ(KEY(p2), 2);
813}
814
815TEST(BinNodeUtils, InsertRootRecInsertsAndRotatesToRoot)
816{
817 NodePool pool;
819 for (int k : {2, 1, 3})
820 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
821
822 auto * p = pool.make(4);
823 auto * new_root = insert_root_rec(root, p);
824 ASSERT_NE(new_root, BinNode<int>::NullPtr);
825 root = new_root;
826
827 EXPECT_EQ(KEY(root), 4);
828 assert_bst_and_inorder_sorted(root);
829}
830
831TEST(BinNodeUtils, InsertRootRecRejectsDuplicate)
832{
833 NodePool pool;
835 for (int k : {2, 1, 3})
836 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
837
838 const auto before = inorder(root);
839 auto * dup = pool.make(2);
841 EXPECT_EQ(inorder(root), before);
842}
843
844TEST(BinNodeUtils, InsertRootRequiresKeyAbsent)
845{
846 NodePool pool;
848 for (int k : {2, 1, 3})
849 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
850
851 auto * existing = pool.make(2);
852 EXPECT_EQ(insert_root(root, existing), BinNode<int>::NullPtr);
853
854 auto * fresh = pool.make(4);
855 ASSERT_NE(insert_root(root, fresh), BinNode<int>::NullPtr);
856 EXPECT_EQ(KEY(root), 4);
857 assert_bst_and_inorder_sorted(root);
858}
859
860TEST(BinNodeUtils, InsertDupRootAlwaysInserts)
861{
862 NodePool pool;
864 for (int k : {2, 1, 3})
865 ASSERT_NE(insert_in_bst(root, pool.make(k)), BinNode<int>::NullPtr);
866
867 auto * dup = pool.make(2);
869 assert_bst_and_inorder_sorted(root);
870}
871
872TEST(BinNodeUtils, RemoveFromBstRespectsComparator)
873{
874 struct Greater
875 {
876 bool operator()(int a, int b) const noexcept { return a > b; }
877 };
878
879 NodePool pool;
881 for (const int k : {1, 2, 3, 4, 5})
882 {
883 auto * inserted = insert_in_bst<BinNode<int>, Greater>(root, pool.make(k), Greater());
884 ASSERT_NE(inserted, BinNode<int>::NullPtr);
885 }
886
887 auto * removed = remove_from_bst<BinNode<int>, Greater>(root, 4, Greater());
888 ASSERT_NE(removed, BinNode<int>::NullPtr);
889 EXPECT_EQ(KEY(removed), 4);
890
891 EXPECT_TRUE((check_bst<BinNode<int>, Greater>(root, Greater())));
892}
893
894TEST(BinNodeUtils, TreeToBitsAndBitsToTreeRoundtripShapeAndKeys)
895{
896 NodePool pool;
897
898 // Build a small explicit shape:
899 // 2
900 // / right
901 // 1 3
902 auto * root = pool.make(2);
903 LLINK(root) = pool.make(1);
904 RLINK(root) = pool.make(3);
905
908
909 int idx = 0;
910 BinNode<int> * rebuilt = bits_to_tree<BinNode<int>>(bits, idx);
911
912 const char * keys[] = {"2", "1", "3", nullptr};
913 int key_idx = 0;
914 load_tree_keys_from_array<BinNode<int>, LoadIntKey>(rebuilt, keys, key_idx);
915
916 EXPECT_EQ(inorder(rebuilt), (std::vector<int>{1, 2, 3}));
917 EXPECT_EQ(tree_to_bits(rebuilt).size(), bits.size());
918
919 delete_tree(rebuilt);
920}
921
922TEST(BinNodeUtils, BitsToTreeThrowsOnInvalidBits)
923{
925 bits.push(0);
926
927 // bits_to_tree should throw domain_error on malformed/truncated bit array
928 EXPECT_THROW((bits_to_tree<BinNode<int>>(bits)), std::domain_error);
929}
930
931TEST(BinNodeUtils, PreorderToBstBuildsValidTree)
932{
933 DynArray<int> pre(7);
934 pre[0] = 5;
935 pre[1] = 3;
936 pre[2] = 2;
937 pre[3] = 4;
938 pre[4] = 7;
939 pre[5] = 6;
940 pre[6] = 8;
941
942 BinNode<int> * root = preorder_to_bst<BinNode<int>>(pre, 0, 6);
943 assert_bst_and_inorder_sorted(root);
944 EXPECT_EQ(inorder(root), (std::vector<int>{2, 3, 4, 5, 6, 7, 8}));
945
947}
948
949TEST(BinNodeUtils, Property_InsertRemoveRandom_StableInvariants)
950{
951 NodePool pool;
953
954 std::mt19937 rng(12345);
955 std::uniform_int_distribution<int> dist(0, 200);
956
957 std::set<int> present;
958
959 for (int i = 0; i < 200; ++i)
960 {
961 int k = dist(rng);
962 auto * p = pool.make(k);
963 auto * ins = insert_in_bst(root, p);
964 if (ins != BinNode<int>::NullPtr)
965 present.insert(k);
966 }
967
968 assert_bst_and_inorder_sorted(root);
969
970 for (int i = 0; i < 100; ++i)
971 {
972 int k = dist(rng);
973 auto * removed = remove_from_bst(root, k);
974 if (removed != BinNode<int>::NullPtr)
975 {
976 EXPECT_EQ(KEY(removed), k);
977 present.erase(k);
978 }
979 assert_bst_and_inorder_sorted(root);
980 }
981}
982
983namespace
984{
985 // Key that counts the instances alive and whose copies throw once a budget
986 // of them is spent.
987 struct Counted_Key
988 {
989 static inline long alive = 0;
990 static inline long copies_left = -1; // -1 means that copies never throw
991
992 int value = 0;
993
994 Counted_Key() { ++alive; }
995 Counted_Key(const int v) : value(v) { ++alive; }
996 Counted_Key(const Counted_Key & key) : value(key.value)
997 {
998 if (copies_left == 0)
999 throw std::runtime_error("copy of key");
1000 if (copies_left > 0)
1001 --copies_left;
1002 ++alive;
1003 }
1004 Counted_Key & operator = (const Counted_Key &) = default;
1005 ~Counted_Key() { --alive; }
1006
1007 bool operator < (const Counted_Key & key) const noexcept
1008 {
1009 return value < key.value;
1010 }
1011 };
1012
1013 // Chain of n nodes with the keys 0, 1, ..., n - 1 from the root down.
1014 // Node i hangs on the left of node i - 1 if goes_left(i), else on its right.
1015 BinNode<int> * build_chain(const int n, const std::function<bool(int)> & goes_left)
1016 {
1017 auto * root = new BinNode<int>(0);
1018 auto * last = root;
1019 for (int i = 1; i < n; ++i)
1020 {
1021 auto * p = new BinNode<int>(i);
1022 (goes_left(i) ? LLINK(last) : RLINK(last)) = p;
1023 last = p;
1024 }
1025 return root;
1026 }
1027
1028 // Number of nodes of a chain that differ, in key or in side, from the
1029 // chain that build_chain(n, goes_left) builds. Walks without recursion.
1030 size_t chain_mismatches(BinNode<int> * root, const int n,
1031 const std::function<bool(int)> & goes_left)
1032 {
1033 size_t mismatches = 0;
1034 auto * p = root;
1035 for (int i = 0; i < n; ++i)
1036 {
1037 if (p == BinNode<int>::NullPtr)
1038 return mismatches + static_cast<size_t>(n - i);
1039 if (KEY(p) != i)
1040 ++mismatches;
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);
1043 if ((LLINK(p) != BinNode<int>::NullPtr) != left or
1044 (RLINK(p) != BinNode<int>::NullPtr) != right)
1045 ++mismatches;
1046 p = left ? LLINK(p) : RLINK(p);
1047 }
1048 return mismatches;
1049 }
1050} // namespace
1051
1052// A recursion as deep as the tree exhausts the call stack with degenerate
1053// trees of this size, and the destruction is in the path of the destructors.
1054TEST(BinNodeUtils, DegenerateTreesAreMeasuredCopiedAndDestroyedWithoutRecursion)
1055{
1056 constexpr int n = 1'000'000;
1057 const std::function<bool(int)> shapes[] =
1058 {
1059 [] (int) { return true; }, // left chain
1060 [] (int) { return false; }, // right chain
1061 [] (const int i) { return i % 2 == 0; } // zigzag
1062 };
1063
1064 for (const auto & goes_left : shapes)
1065 {
1066 auto * root = build_chain(n, goes_left);
1067 EXPECT_EQ(computeHeightRec(root), static_cast<size_t>(n));
1068
1069 auto * copy = copyRec(root);
1070 EXPECT_EQ(chain_mismatches(copy, n, goes_left), 0u);
1071 EXPECT_EQ(chain_mismatches(root, n, goes_left), 0u); // the source is intact
1072 EXPECT_EQ(computeHeightRec(copy), static_cast<size_t>(n));
1073
1075 EXPECT_EQ(copy, BinNode<int>::NullPtr);
1077 EXPECT_EQ(root, BinNode<int>::NullPtr);
1078 }
1079}
1080
1081// A right spine with a leaf on the left of every node. It is much taller
1082// than the bound of the recursions, and a traversal that follows the spine
1083// defers one subtree per level, many more than the stacks keep inline.
1084TEST(BinNodeUtils, CombTreeIsTallerThanTheBoundOfTheRecursions)
1085{
1086 constexpr int levels = 100'000;
1087 ASSERT_GT(static_cast<size_t>(levels), Bin_Tree_Depth_Bound);
1088
1089 auto * root = new BinNode<int>(0);
1090 auto * spine = root;
1091 for (int i = 0; i < levels; ++i)
1092 {
1093 LLINK(spine) = new BinNode<int>(-i - 1);
1094 if (i + 1 < levels)
1095 {
1096 RLINK(spine) = new BinNode<int>(i + 1);
1097 spine = RLINK(spine);
1098 }
1099 }
1100
1101 EXPECT_EQ(computeHeightRec(root), static_cast<size_t>(levels) + 1);
1102
1103 auto * copy = copyRec(root);
1104 size_t mismatches = 0;
1105 auto * p = copy;
1106 for (int i = 0; i < levels; ++i)
1107 {
1108 ASSERT_NE(p, BinNode<int>::NullPtr);
1109 auto * leaf = LLINK(p);
1110 if (KEY(p) != i or leaf == BinNode<int>::NullPtr or KEY(leaf) != -i - 1 or
1112 ++mismatches;
1113 p = RLINK(p);
1114 }
1115 EXPECT_EQ(mismatches, 0u);
1116 EXPECT_EQ(p, BinNode<int>::NullPtr);
1117
1120 EXPECT_EQ(copy, BinNode<int>::NullPtr);
1121 EXPECT_EQ(root, BinNode<int>::NullPtr);
1122}
1123
1124TEST(BinNodeUtils, CopyAndDestroyAccountForEveryNode)
1125{
1126 using Node = BinNode<Counted_Key>;
1127 ASSERT_EQ(Counted_Key::alive, 0);
1128
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);
1133 std::shuffle(keys.begin(), keys.end(), rng);
1134
1135 Node * root = Node::NullPtr;
1136 for (const int k : keys)
1137 ASSERT_NE(insert_in_bst(root, new Node(Counted_Key(k))), Node::NullPtr);
1138 const long nodes = static_cast<long>(keys.size());
1139 ASSERT_EQ(Counted_Key::alive, nodes);
1140
1141 // a copy interrupted at any node frees the nodes that it had built
1142 for (long budget = 0; budget < nodes; ++budget)
1143 {
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;
1148 }
1149
1150 Node * copy = copyRec(root);
1151 EXPECT_EQ(Counted_Key::alive, 2 * nodes);
1152 EXPECT_TRUE(areSimilar(root, copy));
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);
1158
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);
1165}
1166
1167// The nodes live in storage that the test owns, as the nodes of an arena
1168// do: only the destructors of the keys must run, once each.
1169TEST(BinNodeUtils, KeyDestructorsRunOnceOnADegenerateTreeWithoutRecursion)
1170{
1171 using Node = BinNode<Counted_Key>;
1172 constexpr int n = 1'000'000;
1173 ASSERT_EQ(Counted_Key::alive, 0);
1174
1175 std::vector<void *> storage;
1176 storage.reserve(n);
1177 Node * root = Node::NullPtr;
1178 Node * last = nullptr;
1179 for (int i = 0; i < n; ++i)
1180 {
1181 storage.push_back(::operator new(sizeof(Node)));
1182 auto * p = new (storage.back()) Node(Counted_Key(i));
1183 if (last == nullptr)
1184 root = p;
1185 else if (i % 3 == 0)
1186 RLINK(last) = p;
1187 else
1188 LLINK(last) = p;
1189 last = p;
1190 }
1191 ASSERT_EQ(Counted_Key::alive, n);
1192
1194
1195 EXPECT_EQ(root, Node::NullPtr);
1196 EXPECT_EQ(Counted_Key::alive, 0);
1197 for (void * mem : storage)
1198 ::operator delete(mem);
1199}
1200
1201namespace
1202{
1203 // Key whose destructor records its value, to observe the order in which
1204 // the nodes of a tree are destroyed.
1205 struct Recorded_Key
1206 {
1207 static inline std::vector<int> destroyed;
1208
1209 int value = 0;
1210
1211 Recorded_Key() = default;
1212 Recorded_Key(const int v) : value(v) {}
1213 ~Recorded_Key() { destroyed.push_back(value); }
1214 };
1215
1216 int key_value(const int key) { return key; }
1217
1218 int key_value(const Recorded_Key & key) { return key.value; }
1219
1220 // The nodes of a tree in postorder, found without recursion: the order
1221 // node, right, left is the reverse one.
1222 template <class Node>
1223 std::vector<Node *> postorder_nodes(Node * root)
1224 {
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())
1230 {
1231 Node * p = pending.back();
1232 pending.pop_back();
1233 nodes.push_back(p);
1234 if (LLINK(p) != Node::NullPtr)
1235 pending.push_back(LLINK(p));
1236 if (RLINK(p) != Node::NullPtr)
1237 pending.push_back(RLINK(p));
1238 }
1239 std::reverse(nodes.begin(), nodes.end());
1240 return nodes;
1241 }
1242
1243 template <class Node>
1244 std::vector<int> keys_of(const std::vector<Node *> & nodes)
1245 {
1246 std::vector<int> keys;
1247 keys.reserve(nodes.size());
1248 for (Node * p : nodes)
1249 keys.push_back(key_value(KEY(p)));
1250 return keys;
1251 }
1252
1253 // Trees whose nodes hang, most of them, deeper than the bound of the
1254 // recursions. The keys are distinct; the trees need not be ordered.
1255 template <class Node>
1256 std::vector<Node *> deep_trees()
1257 {
1258 constexpr int depth = 3 * static_cast<int>(Bin_Tree_Depth_Bound);
1259 int next_key = 0;
1260 const auto chain = [&next_key] (const int n, const std::function<bool(int)> & goes_left,
1261 Node *& last)
1262 {
1263 auto * root = new Node(next_key++);
1264 last = root;
1265 for (int i = 1; i < n; ++i)
1266 {
1267 auto * p = new Node(next_key++);
1268 (goes_left(i) ? LLINK(last) : RLINK(last)) = p;
1269 last = p;
1270 }
1271 return root;
1272 };
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; };
1276
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));
1282
1283 // a right spine with a leaf on the left of every node, and its mirror
1284 for (const bool leaves_on_left : {true, false})
1285 {
1286 auto * root = new Node(next_key++);
1287 auto * spine = root;
1288 for (int i = 0; i < depth; ++i)
1289 {
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;
1294 spine = below;
1295 }
1296 trees.push_back(root);
1297 }
1298
1299 // a tree of random shape below each kind of chain
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)})
1304 {
1305 auto * root = chain(depth, goes_left, last);
1306 std::vector<Node *> open = {last}; // nodes with a free link
1307 for (int i = 0; i < 2000; ++i)
1308 {
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)
1317 {
1318 open[at] = open.back();
1319 open.pop_back();
1320 }
1321 open.push_back(p);
1322 }
1323 trees.push_back(root);
1324 }
1325
1326 return trees;
1327 }
1328} // namespace
1329
1330// The recursions of 7.0.0 disposed of a node after the nodes below it, the
1331// left subtree first, and with its links already cleared. A node whose
1332// destructor looks at its links, or at what hung from them, depends on it.
1333TEST(BinNodeUtils, NodesAreDisposedInPostorderWithClearedLinksWhateverTheDepth)
1334{
1335 using Node = BinNode<int>;
1336
1337 for (const size_t levels : {Bin_Tree_Depth_Bound, size_t(0), size_t(1), size_t(7)})
1338 {
1339 const auto trees = deep_trees<Node>();
1340 for (size_t t = 0; t < trees.size(); ++t)
1341 {
1342 const auto nodes = postorder_nodes(trees[t]);
1343 const auto expected = keys_of(nodes);
1344
1345 std::vector<int> disposed;
1346 size_t with_links = 0;
1347 const auto dispose = [&] (Node * p) noexcept
1348 {
1349 if (LLINK(p) != Node::NullPtr or RLINK(p) != Node::NullPtr)
1350 ++with_links;
1351 disposed.push_back(KEY(p));
1352 };
1353 dispose_tree_nodes(trees[t], dispose, levels);
1354
1355 EXPECT_EQ(disposed, expected) << "tree " << t << ", levels " << levels;
1356 EXPECT_EQ(with_links, 0u) << "tree " << t << ", levels " << levels;
1357 for (Node * p : nodes)
1358 delete p;
1359 }
1360 }
1361
1362 // the method of the deep subtrees, on its own
1363 const auto trees = deep_trees<Node>();
1364 for (size_t t = 0; t < trees.size(); ++t)
1365 {
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)); };
1369 dispose_tree_by_link_inversion(trees[t], dispose);
1370 EXPECT_EQ(disposed, keys_of(nodes)) << "tree " << t;
1371 for (Node * p : nodes)
1372 delete p;
1373 }
1374
1375 size_t calls = 0;
1376 const auto count = [&calls] (Node *) noexcept { ++calls; };
1377 dispose_tree_by_link_inversion(Node::NullPtr, count);
1378 dispose_tree_nodes(Node::NullPtr, count);
1379 EXPECT_EQ(calls, 0u);
1380}
1381
1382TEST(BinNodeUtils, DestroyRecFreesTheNodesInPostorderWhateverTheDepth)
1383{
1385
1386 auto trees = deep_trees<Node>();
1387 for (size_t t = 0; t < trees.size(); ++t)
1388 {
1389 const auto expected = keys_of(postorder_nodes(trees[t]));
1390 Recorded_Key::destroyed.clear();
1391 destroyRec(trees[t]);
1392 EXPECT_EQ(trees[t], Node::NullPtr);
1393 EXPECT_EQ(Recorded_Key::destroyed, expected) << "tree " << t;
1394 }
1395 Recorded_Key::destroyed.clear();
1396}
1397
1398// With the nodes in an arena only the keys are destroyed, and the nodes
1399// stay where they are: their links must not be left pointing to each other.
1400TEST(BinNodeUtils, KeyDestructorsRunInPostorderAndLeaveTheLinksCleared)
1401{
1403
1404 auto trees = deep_trees<Node>();
1405 for (size_t t = 0; t < trees.size(); ++t)
1406 {
1407 const auto nodes = postorder_nodes(trees[t]);
1408 const auto expected = keys_of(nodes);
1409 Recorded_Key::destroyed.clear();
1410 callKeyDestructorsRec(trees[t]);
1411 EXPECT_EQ(trees[t], Node::NullPtr);
1412 EXPECT_EQ(Recorded_Key::destroyed, expected) << "tree " << t;
1413
1414 size_t with_links = 0;
1415 for (Node * p : nodes)
1416 {
1417 if (LLINK(p) != Node::NullPtr or RLINK(p) != Node::NullPtr)
1418 ++with_links;
1419 ::operator delete(p); // the key is already destroyed
1420 }
1421 EXPECT_EQ(with_links, 0u) << "tree " << t;
1422 }
1423 Recorded_Key::destroyed.clear();
1424}
bool operator<(const Time &l, const Time &r)
Definition ah-time.H:143
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
size_t size_t int32_t value
Definition ca-c-api.h:116
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.
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.
Key & get_key() noexcept
void reset() noexcept
Contiguous array of bits.
Definition bitArray.H:201
Dynamic doubly linked list with O(1) size and bidirectional access.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
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.
Definition ah-dry.H:663
Node * make(int key)
Definition rand-tree.cc:88
#define TEST(name)
static mt19937 rng
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)
Definition gmpfrxx.h:4138
void delete_tree(Tree_Node< T > *node)
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynList< typename GT::Node * > in_nodes(typename GT::Node *p, SA sa=SA())
Return the nodes connected to the filtered incoming arcs to p.
Definition tpl_graph.H:2606
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.
Definition ahAlgo.H:584
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.
Definition ahAlgo.H:127
void callKeyDestructorsRec(Node *&root) noexcept
Traverses the tree and calls key's destructors.
DynList< int > l1
DynList< int > l2
#define RLINK(i, n)
int keys[]
#define LLINK(i, n)
DynArray< int > inorder
static int * k
Gsl_Compatible_Rng r
Utility functions for binary tree operations.
Basic binary tree node definitions.
Lazy and scalable dynamic array implementation.
DynList< int > l