Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tree_verifiers_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 / \ | | ___ _ __ | |__ __ __
5 / _ \ | |/ _ \ '_ \| '_ \ ____\ \ /\ / /
6 / ___ \| | __/ |_) | | | |_____\ V V /
7 /_/ \_\_|\___| .__/|_| |_| \_/\_/
8 |_|
9
10 This file is part of Aleph-w library
11
12 Copyright (c) 2002-2026 Leandro Rabindranath Leon
13
14 Permission is hereby granted, free of charge, to any person obtaining a copy
15 of this software and associated documentation files (the "Software"), to deal
16 in the Software without restriction, including without limitation the rights
17 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18 copies of the Software, and to permit persons to whom the Software is
19 furnished to do so, subject to the following conditions:
20
21 The above copyright notice and this permission notice shall be included in all
22 copies or substantial portions of the Software.
23
24 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 SOFTWARE.
31*/
32
50
51#include <functional>
52#include <utility>
53
54#include <tpl_dynSetTree.H>
55
56using namespace Aleph;
57using namespace search_trees_test;
58
59namespace
60{
61 // A tree built by hand. `node(k, l, r)` makes the node of key `k` over the
62 // subtrees `l` and `r`, where a null pointer is the empty tree.
63 template <class Node>
64 class Hand_Tree
65 {
66 Node_Pool<Node> pool;
67
68 public:
69 Node * node(const int key, Node * l = nullptr, Node * r = nullptr)
70 {
71 Node * p = pool.make(key);
72 if (l != nullptr)
73 LLINK(p) = l;
74 if (r != nullptr)
75 RLINK(p) = r;
76 return p;
77 }
78
79 Node * black(const int key, Node * l = nullptr, Node * r = nullptr)
80 {
81 Node * p = node(key, l, r);
82 COLOR(p) = BLACK;
83 return p;
84 }
85
86 Node * red(const int key, Node * l = nullptr, Node * r = nullptr)
87 {
88 Node * p = node(key, l, r);
89 COLOR(p) = RED;
90 return p;
91 }
92
93 Node * with_priority(const unsigned long priority, const int key,
94 Node * l = nullptr, Node * r = nullptr)
95 {
96 Node * p = node(key, l, r);
97 p->getPriority() = priority;
98 return p;
99 }
100 };
101
102 // Writes in every node the size of its subtree.
103 template <class Node>
104 size_t set_counters(Node * p) noexcept
105 {
106 if (p == Node::NullPtr)
107 return 0;
108 const size_t n = set_counters(LLINK(p)) + set_counters(RLINK(p)) + 1;
109 p->getCount() = n;
110 return n;
111 }
112
113 // Writes in every node its balance factor; returns the height.
114 template <class Node>
115 int set_balance_factors(Node * p) noexcept
116 {
117 if (p == Node::NullPtr)
118 return 0;
119 const int hl = set_balance_factors(LLINK(p));
120 const int hr = set_balance_factors(RLINK(p));
121 DIFF(p) = static_cast<signed char>(hr - hl);
122 return 1 + (hl > hr ? hl : hr);
123 }
124
125 // The counters of a hand-made tree, where its nodes have them.
126 template <class Node>
127 Node * counted(Node * root) noexcept
128 {
129 if constexpr (Counted_Node<Node>)
130 set_counters(root);
131 return root;
132 }
133
134 // What `Tree::verify()` says of the tree of root `root`.
135 template <class Tree>
136 bool verified_by(typename Tree::Node * root)
137 {
138 Tree tree;
139 tree.getRoot() = root;
140 const bool ok = tree.verify();
141 tree.getRoot() = Tree::Node::NullPtr;
142 return ok;
143 }
144
145 bool is_red_black_tree_of(RbNode<int> * root) { return is_red_black_tree(root); }
146 bool is_red_black_tree_of(RbNodeRk<int> * root) { return is_red_black_tree_rk(root); }
147
148 bool has_equal_black_heights(RbNode<int> * root)
149 {
150 int max = -1;
152 }
153
154 bool has_equal_black_heights(RbNodeRk<int> * root)
155 {
156 int max = -1;
158 }
159
160 bool is_red_black_bst_of(RbNode<int> * root)
161 {
163 return is_red_black_bst(root, cmp);
164 }
165
166 bool is_red_black_bst_of(RbNodeRk<int> * root)
167 {
170 }
171
172 bool is_avl_of(AvlNode<int> * root) { return is_avl(root); }
173 bool is_avl_of(AvlNodeRk<int> * root) { return is_avl_rk(root); }
174
175 // The nodes of a tree in order, each one with its parent (the null
176 // pointer for the root).
177 template <class Node>
178 void collect(Node * p, Node * parent, std::vector<std::pair<Node *, Node *>> & out)
179 {
180 if (p == Node::NullPtr)
181 return;
182 collect(LLINK(p), p, out);
183 out.emplace_back(p, parent);
184 collect(RLINK(p), p, out);
185 }
186
187 // A tree of `num_keys` nodes built by the insertions of its type, with the
188 // keys 10, 20, 30... in an order that mixes them.
189 template <class Tree>
190 class Built_Tree
191 {
192 public:
193 using Node = typename Tree::Node;
194
195 static constexpr int num_keys = 40;
196
197 Tree tree;
198 std::vector<std::pair<Node *, Node *>> nodes; // in order, with parents
199
200 Built_Tree()
201 {
202 if constexpr (Seeded_Tree<Tree>)
203 tree.set_seed(20260710);
204
205 // 41 is prime, so i -> 17 i mod 41 visits 1 ... 40 once each
206 for (int i = 1; i <= num_keys; ++i)
207 if (tree.insert(pool.make(10 * (17 * i % (num_keys + 1)))) == nullptr)
208 ADD_FAILURE() << "a new key was not inserted";
209
210 collect(tree.getRoot(), static_cast<Node *>(nullptr), nodes);
211 }
212
213 private:
214 Node_Pool<Node> pool;
215 };
216
217 template <class Node>
218 class RedBlackNodes : public ::testing::Test
219 {
220 protected:
221 Hand_Tree<Node> t;
222 };
223
224 using Red_Black_Node_Types = ::testing::Types<RbNode<int>, RbNodeRk<int>>;
225 TYPED_TEST_SUITE(RedBlackNodes, Red_Black_Node_Types);
226
227 template <class Node>
228 class AvlNodes : public ::testing::Test
229 {
230 protected:
231 Hand_Tree<Node> t;
232
233 // The factors and, where the node has them, the counters.
234 Node * finished(Node * root)
235 {
236 set_balance_factors(root);
237 return counted(root);
238 }
239 };
240
241 using Avl_Node_Types = ::testing::Types<AvlNode<int>, AvlNodeRk<int>>;
242 TYPED_TEST_SUITE(AvlNodes, Avl_Node_Types);
243
244 template <class Tree> class AnyTreeVerify : public ::testing::Test {};
245 template <class Tree> class RankedTreeVerify : public ::testing::Test {};
246 template <class Tree> class RedBlackTreeVerify : public ::testing::Test {};
247 template <class Tree> class AvlTreeVerify : public ::testing::Test {};
248 template <class Tree> class TreapVerify : public ::testing::Test {};
249
250 TYPED_TEST_SUITE(AnyTreeVerify, All_Trees, Tree_Names);
251 TYPED_TEST_SUITE(RankedTreeVerify, Ranked_Trees, Tree_Names);
252 TYPED_TEST_SUITE(RedBlackTreeVerify, Red_Black_Trees, Tree_Names);
253 TYPED_TEST_SUITE(AvlTreeVerify, Avl_Trees, Tree_Names);
254 TYPED_TEST_SUITE(TreapVerify, Treaps, Tree_Names);
255}
256
257// ---------------------------------------------------------------------------
258// Red-black trees built by hand
259// ---------------------------------------------------------------------------
260
261TYPED_TEST(RedBlackNodes, AcceptsAValidTree)
262{
263 auto & t = this->t;
264 auto * root = counted(t.black(8,
265 t.red(4, t.black(2, t.red(1)), t.black(6)),
266 t.red(12, t.black(10), t.black(14, nullptr, t.red(15)))));
267
268 EXPECT_TRUE(is_red_black_tree_of(root));
269 EXPECT_TRUE(has_equal_black_heights(root));
270 EXPECT_TRUE(is_red_black_bst_of(root));
271}
272
273TYPED_TEST(RedBlackNodes, AcceptsTheEmptyTreeAndASingleNode)
274{
275 using Node = TypeParam;
276
277 EXPECT_TRUE(is_red_black_tree_of(Node::NullPtr));
278 EXPECT_TRUE(is_red_black_bst_of(Node::NullPtr));
279 EXPECT_TRUE(is_red_black_tree_of(counted(this->t.black(1))));
280 EXPECT_TRUE(is_red_black_tree_of(counted(this->t.red(1))));
281}
282
283// The trees of the library do not force the root to be black.
284TYPED_TEST(RedBlackNodes, AcceptsARedRoot)
285{
286 auto & t = this->t;
287 auto * root = counted(t.red(8,
288 t.black(4, t.red(2), t.red(6)),
289 t.black(12, nullptr, t.red(14))));
290
291 EXPECT_TRUE(is_red_black_tree_of(root));
292 EXPECT_TRUE(is_red_black_bst_of(root));
293}
294
295// The two red nodes are at depths 2 and 3, and every path has two black
296// nodes: only a check of every node sees the defect.
297TYPED_TEST(RedBlackNodes, RejectsARedNodeWithARedChildBelowTheRoot)
298{
299 auto & t = this->t;
300 auto * root = counted(t.black(8,
301 t.black(4, t.red(2, t.red(1)), t.red(6)),
302 t.black(12, t.red(10), t.red(14))));
303
304 ASSERT_TRUE(has_equal_black_heights(root));
305 EXPECT_FALSE(is_red_black_tree_of(root));
306 EXPECT_FALSE(is_red_black_bst_of(root));
307}
308
309TYPED_TEST(RedBlackNodes, RejectsARedRightChildOfARedNode)
310{
311 auto & t = this->t;
312 auto * root = counted(t.black(8,
313 t.black(4),
314 t.black(12, nullptr, t.red(14, nullptr, t.red(15)))));
315
316 EXPECT_FALSE(is_red_black_tree_of(root));
317}
318
319// The path that ends at the empty right subtree of the root crosses one
320// black node; the one through its only child crosses two. No leaf shows it.
321TYPED_TEST(RedBlackNodes, RejectsABlackNodeWithASingleBlackChild)
322{
323 auto & t = this->t;
324 auto * root = counted(t.black(8, t.black(4)));
325
326 EXPECT_FALSE(has_equal_black_heights(root));
327 EXPECT_FALSE(is_red_black_tree_of(root));
328 EXPECT_FALSE(is_red_black_bst_of(root));
329}
330
331TYPED_TEST(RedBlackNodes, RejectsASingleBlackChildDeepInTheTree)
332{
333 auto & t = this->t;
334 auto * root = counted(t.black(8,
335 t.black(4, t.red(2), t.red(6, nullptr, t.black(7))),
336 t.black(12)));
337
338 EXPECT_FALSE(has_equal_black_heights(root));
339 EXPECT_FALSE(is_red_black_tree_of(root));
340}
341
342TYPED_TEST(RedBlackNodes, RejectsSubtreesWithDifferentBlackHeights)
343{
344 auto & t = this->t;
345 auto * root = counted(t.black(8,
346 t.black(4, t.black(2), t.black(6)),
347 t.black(12)));
348
349 EXPECT_FALSE(has_equal_black_heights(root));
350 EXPECT_FALSE(is_red_black_tree_of(root));
351}
352
353TYPED_TEST(RedBlackNodes, RejectsAColorThatIsNeitherRedNorBlack)
354{
355 auto & t = this->t;
356 auto * odd = t.black(2);
357 auto * root = counted(t.black(8, t.red(4, odd, t.black(6)), t.black(12)));
358 ASSERT_TRUE(is_red_black_tree_of(root));
359
360 COLOR(odd) = 7;
361 EXPECT_FALSE(is_red_black_tree_of(root));
362}
363
364TYPED_TEST(RedBlackNodes, RejectsKeysOutOfOrder)
365{
366 auto & t = this->t;
367 auto * root = counted(t.black(8,
368 t.red(4, t.black(2), t.black(9)), // 9 > 8
369 t.red(12, t.black(10), t.black(14))));
370
371 EXPECT_TRUE(is_red_black_tree_of(root)); // the colors are right
372 EXPECT_FALSE(is_red_black_bst_of(root));
373}
374
375TEST(RedBlackRankNodes, RejectsAWrongCounterBelowTheRoot)
376{
377 Hand_Tree<RbNodeRk<int>> t;
378 auto * deep = t.black(2, t.red(1));
379 auto * root = counted(t.black(8,
380 t.red(4, deep, t.black(6)),
381 t.red(12, t.black(10), t.black(14))));
382 ASSERT_TRUE(is_red_black_tree_rk(root));
383
384 ++deep->getCount();
385 EXPECT_FALSE(is_red_black_tree_rk(root));
386 EXPECT_FALSE(check_rank_tree(root));
387}
388
389TEST(RedBlackTreesVerify, RejectTheHandMadeDefects)
390{
391 Hand_Tree<RbNode<int>> t;
392 auto * red_red = t.black(8,
393 t.black(4, t.red(2, t.red(1)), t.red(6)),
394 t.black(12, t.red(10), t.red(14)));
395 auto * single_black_child = t.black(8, t.black(4));
396 auto * out_of_order = t.black(1, t.red(2), t.red(3));
397 auto * valid = t.black(2, t.red(1), t.red(3));
398 auto * red_root = t.red(2, t.black(1), t.black(3));
399
400 for (auto * root : {valid, red_root})
401 {
402 EXPECT_TRUE(verified_by<Rb_Tree<int>>(root));
403 EXPECT_TRUE(verified_by<TdRbTree<int>>(root));
404 EXPECT_TRUE(verified_by<HtdRbTree<int>>(root));
405 }
406
407 for (auto * root : {red_red, single_black_child, out_of_order})
408 {
409 EXPECT_FALSE(verified_by<Rb_Tree<int>>(root)) << "root " << KEY(root);
410 EXPECT_FALSE(verified_by<TdRbTree<int>>(root)) << "root " << KEY(root);
411 EXPECT_FALSE(verified_by<HtdRbTree<int>>(root)) << "root " << KEY(root);
412 }
413}
414
415TEST(RedBlackRankTreesVerify, RejectTheHandMadeDefects)
416{
417 Hand_Tree<RbNodeRk<int>> t;
418 auto * red_red = counted(t.black(8,
419 t.black(4, t.red(2, t.red(1)), t.red(6)),
420 t.black(12, t.red(10), t.red(14))));
421 auto * single_black_child = counted(t.black(8, t.black(4)));
422 auto * out_of_order = counted(t.black(1, t.red(2), t.red(3)));
423 auto * miscounted = counted(t.black(2, t.red(1), t.red(3)));
424 miscounted->getCount() = 4;
425 auto * valid = counted(t.black(2, t.red(1), t.red(3)));
426 auto * red_root = counted(t.red(2, t.black(1), t.black(3)));
427
428 for (auto * root : {valid, red_root})
429 {
430 EXPECT_TRUE(verified_by<Rb_Tree_Rk<int>>(root));
431 EXPECT_TRUE(verified_by<TdRbTreeRk<int>>(root));
432 EXPECT_TRUE(verified_by<HtdRbTreeRk<int>>(root));
433 }
434
435 for (auto * root : {red_red, single_black_child, out_of_order, miscounted})
436 {
437 EXPECT_FALSE(verified_by<Rb_Tree_Rk<int>>(root)) << "root " << KEY(root);
438 EXPECT_FALSE(verified_by<TdRbTreeRk<int>>(root)) << "root " << KEY(root);
439 EXPECT_FALSE(verified_by<HtdRbTreeRk<int>>(root)) << "root " << KEY(root);
440 }
441}
442
443TEST(RedBlackTreesVerify, VerifyRedBlackLooksOnlyAtTheColors)
444{
445 Hand_Tree<RbNode<int>> t;
446 auto * out_of_order = t.black(1, t.red(2), t.red(3));
447 auto * single_black_child = t.black(8, t.black(4));
448
449 {
450 HtdRbTree<int> tree;
451 tree.getRoot() = out_of_order;
452 EXPECT_TRUE(tree.verifyRedBlack());
453 EXPECT_FALSE(tree.verify());
454 tree.getRoot() = single_black_child;
455 EXPECT_FALSE(tree.verifyRedBlack());
457 EXPECT_TRUE(tree.verifyRedBlack());
458 }
459 {
460 TdRbTree<int> tree;
461 tree.getRoot() = out_of_order;
462 EXPECT_TRUE(tree.verifyRedBlack());
463 EXPECT_FALSE(tree.verify());
464 tree.getRoot() = single_black_child;
465 EXPECT_FALSE(tree.verifyRedBlack());
467 EXPECT_TRUE(tree.verifyRedBlack());
468 }
469}
470
471// ---------------------------------------------------------------------------
472// AVL trees built by hand
473// ---------------------------------------------------------------------------
474
475TYPED_TEST(AvlNodes, AcceptsAValidTree)
476{
477 auto & t = this->t;
478 auto * root = this->finished(t.node(8,
479 t.node(4, t.node(2, t.node(1)), t.node(6)),
480 t.node(12, nullptr, t.node(14))));
481
482 EXPECT_TRUE(is_avl_of(root));
483 EXPECT_TRUE(is_avl_of(TypeParam::NullPtr));
484 EXPECT_TRUE(is_avl_of(this->finished(t.node(1))));
485}
486
487TYPED_TEST(AvlNodes, RejectsAStoredFactorThatIsNotTheRealOneBelowTheRoot)
488{
489 auto & t = this->t;
490 auto * deep = t.node(2, t.node(1));
491 auto * root = this->finished(t.node(8,
492 t.node(4, deep, t.node(6)),
493 t.node(12, nullptr, t.node(14))));
494 ASSERT_TRUE(is_avl_of(root));
495 ASSERT_EQ(DIFF(deep), -1);
496
497 for (const int wrong : {-2, 0, 1, 2})
498 {
499 DIFF(deep) = static_cast<signed char>(wrong);
500 EXPECT_FALSE(is_avl_of(root)) << "factor " << wrong;
501 }
502
503 DIFF(deep) = -1;
504 EXPECT_TRUE(is_avl_of(root));
505}
506
507// The node of key 12 has a right subtree two levels taller than its left
508// one, whatever its factor claims.
509TYPED_TEST(AvlNodes, RejectsSubtreesWhoseHeightsDifferByTwo)
510{
511 auto & t = this->t;
512 auto * leaning = t.node(12, nullptr, t.node(14, nullptr, t.node(15)));
513 auto * root = this->finished(t.node(8,
514 t.node(4, t.node(2, t.node(1)), t.node(6)),
515 leaning));
516 ASSERT_EQ(DIFF(leaning), 2);
517 EXPECT_FALSE(is_avl_of(root));
518
519 for (const int claimed : {-1, 0, 1})
520 {
521 DIFF(leaning) = static_cast<signed char>(claimed);
522 EXPECT_FALSE(is_avl_of(root)) << "factor " << claimed;
523 }
524}
525
526TEST(AvlRankNodes, RejectsAWrongCounterBelowTheRoot)
527{
528 Hand_Tree<AvlNodeRk<int>> t;
529 auto * deep = t.node(2, t.node(1));
530 auto * root = t.node(8, t.node(4, deep, t.node(6)), t.node(12, nullptr, t.node(14)));
531 set_balance_factors(root);
532 set_counters(root);
533 ASSERT_TRUE(is_avl_rk(root));
534
535 --deep->getCount();
536 EXPECT_FALSE(is_avl_rk(root));
537 EXPECT_FALSE(check_rank_tree(root));
538}
539
540// Balanced, and its factors are right, but 2 is at the left of 1.
541TEST(AvlTreesVerify, RejectKeysOutOfOrder)
542{
543 {
544 Hand_Tree<AvlNode<int>> t;
545 auto * root = t.node(1, t.node(2), t.node(3));
546 ASSERT_TRUE(is_avl(root));
547 EXPECT_FALSE(verified_by<Avl_Tree<int>>(root));
548 EXPECT_TRUE(verified_by<Avl_Tree<int>>(t.node(2, t.node(1), t.node(3))));
549 }
550 {
551 Hand_Tree<AvlNodeRk<int>> t;
552 auto * root = counted(t.node(1, t.node(2), t.node(3)));
553 ASSERT_TRUE(is_avl_rk(root));
554 EXPECT_FALSE(verified_by<Avl_Tree_Rk<int>>(root));
555 EXPECT_TRUE(verified_by<Avl_Tree_Rk<int>>(counted(t.node(2, t.node(1), t.node(3)))));
556 }
557}
558
559// ---------------------------------------------------------------------------
560// Treaps and ranked trees built by hand
561// ---------------------------------------------------------------------------
562
563TEST(TreapNodes, IsTreapChecksTheHeapOrderAtEveryNode)
564{
565 Hand_Tree<TreapNode<int>> t;
566 auto * deep = t.with_priority(30, 1);
567 auto * root = t.with_priority(10, 8,
568 t.with_priority(20, 4, t.with_priority(25, 2, deep)),
569 t.with_priority(15, 12));
570 EXPECT_TRUE(is_treap(root));
571 EXPECT_TRUE(is_treap(TreapNode<int>::NullPtr));
572
573 PRIO(deep) = 24; // less than the priority of its parent
574 EXPECT_FALSE(is_treap(root));
575
576 PRIO(deep) = 25; // equal priorities keep the heap order
577 EXPECT_TRUE(is_treap(root));
578}
579
580// A heap on the priorities, but 2 is at the left of 1.
581TEST(TreapsVerify, RejectKeysOutOfOrder)
582{
583 {
584 Hand_Tree<TreapNode<int>> t;
585 auto * root = t.with_priority(1, 1, t.with_priority(2, 2), t.with_priority(3, 3));
586 ASSERT_TRUE(is_treap(root));
587 EXPECT_FALSE(verified_by<Treap<int>>(root));
588 EXPECT_TRUE(verified_by<Treap<int>>(t.with_priority(1, 2, t.with_priority(2, 1),
589 t.with_priority(3, 3))));
590 }
591 {
592 Hand_Tree<Treap_Rk_Node<int>> t;
593 auto * root = counted(t.with_priority(1, 1, t.with_priority(2, 2), t.with_priority(3, 3)));
594 ASSERT_TRUE(is_treap(root));
595 EXPECT_FALSE(verified_by<Treap_Rk<int>>(root));
596 EXPECT_TRUE(verified_by<Treap_Rk<int>>(counted(t.with_priority(1, 2, t.with_priority(2, 1),
597 t.with_priority(3, 3)))));
598 }
599}
600
601TEST(TreapsVerify, TreapRkRejectsAWrongCounter)
602{
603 Hand_Tree<Treap_Rk_Node<int>> t;
604 auto * leaf = t.with_priority(3, 1);
605 auto * root = counted(t.with_priority(1, 4, t.with_priority(2, 2, leaf), t.with_priority(5, 6)));
606 ASSERT_TRUE(verified_by<Treap_Rk<int>>(root));
607
608 leaf->getCount() = 2;
609 EXPECT_FALSE(verified_by<Treap_Rk<int>>(root));
610}
611
612TEST(RankedNodes, CheckRankTreeChecksEveryCounter)
613{
614 Hand_Tree<BinNodeXt<int>> t;
615 auto * deep = t.node(2, t.node(1));
616 auto * root = t.node(8, t.node(4, deep, t.node(6)), t.node(12));
617 set_counters(root);
618 EXPECT_TRUE(check_rank_tree(root));
620
621 for (const size_t wrong : {size_t(0), size_t(1), size_t(3)})
622 {
623 COUNT(deep) = wrong;
624 EXPECT_FALSE(check_rank_tree(root)) << "counter " << wrong;
625 }
626
627 COUNT(deep) = 2;
628 EXPECT_TRUE(check_rank_tree(root));
629}
630
631TEST(RankedTreesVerify, RandTreeAndSplayTreeRkRejectKeysOutOfOrder)
632{
633 {
634 Hand_Tree<Rand_Tree<int>::Node> t;
635 EXPECT_FALSE(verified_by<Rand_Tree<int>>(counted(t.node(1, t.node(2), t.node(3)))));
636 EXPECT_TRUE(verified_by<Rand_Tree<int>>(counted(t.node(2, t.node(1), t.node(3)))));
637 }
638 {
639 Hand_Tree<Splay_Tree_Rk<int>::Node> t;
640 EXPECT_FALSE(verified_by<Splay_Tree_Rk<int>>(counted(t.node(1, t.node(2), t.node(3)))));
641 EXPECT_TRUE(verified_by<Splay_Tree_Rk<int>>(counted(t.node(2, t.node(1), t.node(3)))));
642 }
643}
644
645// A key that is in order with its parent but not with an ancestor further
646// up: 9 is a right child of 4, at the left of 8.
647TEST(BstOrder, CheckBstComparesWithEveryAncestor)
648{
649 Hand_Tree<BinNode<int>> t;
650 auto * stray = t.node(6);
651 auto * root = t.node(8, t.node(4, t.node(2), stray), t.node(12));
652 EXPECT_TRUE(check_bst(root));
653
654 KEY(stray) = 9;
655 EXPECT_FALSE(check_bst(root));
656 EXPECT_FALSE(verified_by<BinTree<int>>(root));
657 EXPECT_FALSE(verified_by<Splay_Tree<int>>(root));
658}
659
660TEST(BstOrder, CheckBstFollowsTheComparator)
661{
662 Hand_Tree<BinNode<int>> t;
663 auto * descending = t.node(8, t.node(12), t.node(4));
664
665 EXPECT_FALSE(check_bst(descending));
666 EXPECT_TRUE(check_bst(descending, std::greater<int>()));
667 EXPECT_TRUE(check_bst(t.node(5, t.node(5), t.node(5)))); // repeated keys
668}
669
670// ---------------------------------------------------------------------------
671// One defect at a time in the trees that each type builds
672// ---------------------------------------------------------------------------
673
674TYPED_TEST(AnyTreeVerify, AcceptsTheEmptyTreeAndWhatInsertBuilds)
675{
676 EXPECT_TRUE(TypeParam().verify());
677
678 Built_Tree<TypeParam> built;
679 ASSERT_EQ(built.nodes.size(), size_t(built.num_keys));
680 EXPECT_TRUE(built.tree.verify());
681}
682
683TYPED_TEST(AnyTreeVerify, RejectsTwoNeighborKeysSwappedAnywhere)
684{
685 Built_Tree<TypeParam> built;
686 auto & nodes = built.nodes;
687 ASSERT_TRUE(built.tree.verify());
688
689 for (size_t i = 0; i + 1 < nodes.size(); ++i)
690 {
691 auto * p = nodes[i].first;
692 auto * q = nodes[i + 1].first;
693 std::swap(KEY(p), KEY(q));
694 EXPECT_FALSE(built.tree.verify()) << "keys " << KEY(q) << " and " << KEY(p);
695 std::swap(KEY(p), KEY(q));
696 }
697
698 EXPECT_TRUE(built.tree.verify());
699}
700
701TYPED_TEST(RankedTreeVerify, RejectsAWrongCounterAnywhere)
702{
703 Built_Tree<TypeParam> built;
704 ASSERT_TRUE(built.tree.verify());
705
706 for (auto & [p, parent] : built.nodes)
707 {
708 const size_t count = p->getCount();
709
710 p->getCount() = count + 1;
711 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p) << ", one more";
712
713 p->getCount() = count - 1;
714 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p) << ", one less";
715
716 p->getCount() = count;
717 }
718
719 EXPECT_TRUE(built.tree.verify());
720}
721
722TYPED_TEST(RedBlackTreeVerify, RejectsARecoloredNodeAnywhere)
723{
724 Built_Tree<TypeParam> built;
725 ASSERT_TRUE(built.tree.verify());
726
727 size_t reds = 0, blacks = 0;
728 for (auto & [p, parent] : built.nodes)
729 {
730 const auto color = COLOR(p);
731 (color == RED ? reds : blacks)++;
732
733 COLOR(p) = 2;
734 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p) << ", no color";
735
736 // Recoloring any node but the root changes the black nodes of the
737 // paths through it and leaves the other paths as they were.
738 if (parent != nullptr)
739 {
740 COLOR(p) = color == RED ? BLACK : RED;
741 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p) << ", recolored";
742 }
743
744 COLOR(p) = color;
745 }
746
747 EXPECT_GT(reds, 0u);
748 EXPECT_GT(blacks, 1u);
749 EXPECT_TRUE(built.tree.verify());
750}
751
752TYPED_TEST(AvlTreeVerify, RejectsAWrongBalanceFactorAnywhere)
753{
754 Built_Tree<TypeParam> built;
755 ASSERT_TRUE(built.tree.verify());
756
757 for (auto & [p, parent] : built.nodes)
758 {
759 const signed char factor = DIFF(p);
760
761 for (const int wrong : {-2, -1, 0, 1, 2})
762 if (wrong != factor)
763 {
764 DIFF(p) = static_cast<signed char>(wrong);
765 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p) << ", factor " << wrong;
766 }
767
768 DIFF(p) = factor;
769 }
770
771 EXPECT_TRUE(built.tree.verify());
772}
773
774TYPED_TEST(TreapVerify, RejectsAPriorityBelowTheOneOfItsParentAnywhere)
775{
776 Built_Tree<TypeParam> built;
777 ASSERT_TRUE(built.tree.verify());
778
779 size_t checked = 0;
780 for (auto & [p, parent] : built.nodes)
781 {
782 if (parent == nullptr or PRIO(parent) == 0)
783 continue;
784
785 const unsigned long priority = PRIO(p);
786 PRIO(p) = PRIO(parent) - 1;
787 EXPECT_FALSE(built.tree.verify()) << "key " << KEY(p);
788 PRIO(p) = priority;
789 ++checked;
790 }
791
792 EXPECT_GE(checked + 2, built.nodes.size());
793 EXPECT_TRUE(built.tree.verify());
794}
795
796// ---------------------------------------------------------------------------
797// DynSetTree
798// ---------------------------------------------------------------------------
799
800namespace
801{
802 // The order of a set is checked with the comparator of the set.
803 template <template <typename, class> class Tree>
804 void check_set_in_descending_order()
805 {
807 for (int i = 1; i <= 40; ++i)
808 set.insert(17 * i % 41);
809
810 EXPECT_TRUE(set.verify());
811 EXPECT_EQ(set.size(), 40u);
812 EXPECT_EQ(set.min(), 40);
813 EXPECT_EQ(set.max(), 1);
814 }
815}
816
817# define CHECK_SET_IN_DESCENDING_ORDER(Tree) \
818 { \
819 SCOPED_TRACE(#Tree); \
820 check_set_in_descending_order<Tree>(); \
821 }
822
840
841// ---------------------------------------------------------------------------
842// A comparator that throws
843// ---------------------------------------------------------------------------
844
845namespace
846{
847 struct Comparator_Error {};
848
849 // Compares as less<int> does, until it is told to fail.
850 struct Fallible_Less
851 {
852 static inline bool fails = false;
853
854 bool operator ()(const int a, const int b) const
855 {
856 if (fails)
857 throw Comparator_Error();
858 return a < b;
859 }
860 };
861
862 // While one lives, Fallible_Less throws.
863 struct Failing_Comparisons
864 {
865 Failing_Comparisons() noexcept { Fallible_Less::fails = true; }
866 ~Failing_Comparisons() { Fallible_Less::fails = false; }
867 };
868
869 using Trees_With_A_Fallible_Comparator = ::testing::Types<
877
878 // The names of those trees, in the same order.
879 struct Fallible_Tree_Names
880 {
881 template <class Tree>
882 static std::string GetName(const int i)
883 {
884 static constexpr const char * names[] = {
885 "BinTree", "Avl_Tree", "Avl_Tree_Rk", "Rb_Tree", "Rb_Tree_Rk",
886 "TdRbTree", "TdRbTreeRk", "HtdRbTree", "HtdRbTreeRk", "Treap",
887 "Treap_Rk", "Rand_Tree", "Splay_Tree", "Splay_Tree_Rk"};
888 return names[i];
889 }
890 };
891}
892
893template <class Tree>
894struct VerifyWithAFallibleComparator : ::testing::Test {};
895
896TYPED_TEST_SUITE(VerifyWithAFallibleComparator, Trees_With_A_Fallible_Comparator,
897 Fallible_Tree_Names);
898
899// verify() compares the keys, so what the comparator throws has to reach the
900// caller: a noexcept verify() would end the program instead.
902{
903 using Tree = TypeParam;
904 static_assert(not noexcept(std::declval<const Tree &>().verify()));
905
907 Tree tree;
908 for (const int key : {4, 2, 6, 1, 3, 5, 7})
909 ASSERT_NE(tree.insert(pool.make(key)), nullptr);
910 ASSERT_TRUE(tree.verify());
911
912 {
913 const Failing_Comparisons failing;
914 EXPECT_THROW((void) tree.verify(), Comparator_Error);
915 }
916
917 EXPECT_TRUE(tree.verify());
918}
bool is_avl(Node *p)
Validate that a tree satisfies AVL properties.
Definition avlNode.H:160
#define DIFF(p)
Access the balance factor of node p.
Definition avlNode.H:95
WeightedDigraph::Node Node
@ KEY
Definition btreepic.C:169
long double hr
Definition btreepic.C:149
size_t size_t int32_t * out
Definition ca-c-api.h:120
Extended AVL node with subtree counter.
Definition avlNodeRk.H:79
Node for extended binary search tree.
Dynamic set backed by balanced binary search trees with automatic memory management.
const Key & min() const
Returns the smallest key contained in the set according to the criterion comparison given.
const size_t & size() const
Returns the cardinality of the set.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
const Key & max() const
Returns the largest key contained in the set according to the criteria comparison given.
bool verify() const
Verify the red-black properties and the order of the keys.
bool verifyRedBlack() const noexcept
Verify that tree satisfies all red-black properties.
Node *& getRoot() noexcept
Get reference to root pointer.
Hybrid top-down/bottom-up red-black tree with rank support.
Hybrid top-down/bottom-up red-black tree.
Definition tpl_hRbTree.H:86
Node *& getRoot() noexcept
Get reference to root pointer.
bool verifyRedBlack() const noexcept
Verify the red-black properties of every node.
bool verify() const
Verify tree is a valid red-black BST.
Extended Red-Black node with subtree counter.
Definition rbNodeRk.H:84
Top-down red-black tree with rank (no virtual destructor).
Top-down red-black tree without virtual destructor.
Declare TreapNode type with 80-byte pool allocation.
Definition treapNode.H:108
Declare AvlNode type with 40-byte pool allocation.
Definition avlNode.H:98
Node for QuadTree spatial data structure.
Definition quadnode.H:95
QuadTree - Hierarchical spatial index for 2D points.
Definition quadtree.H:126
QuadNode Node
Definition quadtree.H:128
Point * insert(Node *&r, const Point &p)
Recursive insert helper.
Definition quadtree.H:281
Declare RbNode type with 128-byte pool allocation.
Definition rbNode.H:116
Owns the nodes of a tree, which does not free them.
#define TEST(name)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
__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
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
bool check_rank_tree(Node *root) noexcept
Return true if root is a valid extended binary tree.
bool check_bst(Node *p, const Compare &cmp=Compare())
Return true if p is a binary search tree.
auto & COUNT(Node *p) noexcept
Return the number of nodes of the tree fron p is root.
unsigned long & PRIO(Node *p) noexcept
Access the priority of a treap node.
Definition treapNode.H:120
void verify()
Main namespace for Aleph-w library functions.
bool is_treap(Node *root) noexcept
Validate that a tree satisfies treap (heap) property.
Definition treapNode.H:144
bool is_red_black_bst_rk(Node *node, Compare &cmp)
Verify that tree rooted at node is a valid red-black BST with counters.
Definition rbNodeRk.H:201
bool is_red_black_tree_rk(Node *node)
Verify if tree is a valid red-black tree with correct counters.
Definition rbNodeRk.H:189
bool is_avl_rk(Node *p)
Verify if tree rooted at p is a valid AVL tree with correct counters.
Definition avlNodeRk.H:124
bool test_black_condition_rk(Node *p, int &max, int bh=0)
Test the black height condition for a red-black tree.
Definition rbNodeRk.H:95
static long & color(typename GT::Node *p)
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
::testing::Types< Avl_Tree_Rk< int >, Rb_Tree_Rk< int >, TdRbTreeRk< int >, HtdRbTreeRk< int >, Treap_Rk< int >, Rand_Tree< int >, Splay_Tree_Rk< int > > Ranked_Trees
The trees whose nodes count the nodes of their subtree.
::testing::Types< BinTree< int >, Avl_Tree< int >, Avl_Tree_Rk< int >, Rb_Tree< int >, Rb_Tree_Rk< int >, TdRbTree< int >, TdRbTreeRk< int >, HtdRbTree< int >, HtdRbTreeRk< int >, Treap< int >, Treap_Rk< int >, Rand_Tree< int >, Splay_Tree< int >, Splay_Tree_Rk< int > > All_Trees
Every binary search tree of the library.
::testing::Types< Rb_Tree< int >, Rb_Tree_Rk< int >, TdRbTree< int >, TdRbTreeRk< int >, HtdRbTree< int >, HtdRbTreeRk< int > > Red_Black_Trees
The red-black trees.
::testing::Types< Treap< int >, Treap_Rk< int > > Treaps
The treaps.
::testing::Types< Avl_Tree< int >, Avl_Tree_Rk< int > > Avl_Trees
The AVL trees.
#define COLOR(p)
Definition quadnode.H:59
bool is_red_black_bst(Node *node, Compare &cmp)
Verify that tree is both a valid RB tree and valid BST.
Definition rbNode.H:251
bool test_black_condition(Node *p, int &max, int bh=0)
Test the black-height property of an RB tree.
Definition rbNode.H:131
#define BLACK
Black color constant.
Definition rbNode.H:80
#define RED
Red color constant (newly inserted nodes are red)
Definition rbNode.H:77
bool is_red_black_tree(Node *node)
Test RB properties for entire subtree.
Definition rbNode.H:234
What the tests of the binary search trees share: the list of tree types, what each node carries,...
Ranked AVL tree with nodes without a virtual destructor.
Definition tpl_avlRk.H:1592
AVL binary search tree with nodes without a virtual destructor.
Definition tpl_avl.H:831
Binary search tree with nodes without virtual destructors,.
Randomized binary search tree.
Red-Black binary search tree with nodes without virtual destructor and with subtree counters for sele...
Definition tpl_rbRk.H:1653
Red-black tree with nodes without virtual destructor.
Extended treap (a special type of randomized binary search tree) which manages selection and splittin...
Treap (a special type of randomized binary search tree) using nodes without virtual destructor.
Definition tpl_treap.H:797
Names the instances of a typed test suite after their tree.
#define RLINK(i, n)
#define LLINK(i, n)
ValueArg< size_t > num_keys
Definition testHash.C:50
Gsl_Compatible_Rng r
Dynamic set implementations based on balanced binary search trees.
DynList< int > l
#define CHECK_SET_IN_DESCENDING_ORDER(Tree)
TYPED_TEST_SUITE(VerifyWithAFallibleComparator, Trees_With_A_Fallible_Comparator, Fallible_Tree_Names)
TYPED_TEST(RedBlackNodes, AcceptsAValidTree)