Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_rb_tree.H
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
54# ifndef TPL_RB_TREE_H
55# define TPL_RB_TREE_H
56
57# include <ahFunction.H>
58# include <tpl_arrayStack.H>
59# include <tpl_binNodeUtils.H>
60# include <rbNode.H>
61# include <ah-concepts.H>
62
63namespace Aleph
64{
65
124template <template <typename> class NodeType, typename Key, class Compare>
125 requires StrictWeakOrder<Compare, Key>
127{
128public:
129 using Node = NodeType<Key>;
130 using key_type = Key;
131 using compare_type = Compare;
132
133private:
137 Compare cmp;
138 size_t num_nodes;
139 static constexpr signed char CmpLess = -1;
140 static constexpr signed char CmpEqual = 0;
141 static constexpr signed char CmpGreater = 1;
142
143 /* The path from the head node to the node an operation works on. Each
144 operation builds it, consumes it and drops it: it lives in the frame
145 of the operation, so the tree never allocates. */
146 // The head node, then at most Node::MaxHeight nodes of the tree.
148
151 Node * search_and_stack_rb(const Key & key,
152 signed char & cmp_result, Path & path)
153 noexcept(nothrow_compare_v<Compare, Key>)
154 {
155 Node *p = root;
156 Node *candidate = nullptr; // Tracks potential duplicate when going right
157 size_t candidate_pos = 0; // Stack size when candidate was set
158
159 path.push(head);
160 do
161 {
162 path.push(p);
163 if (cmp(key, KEY(p))) // key < KEY(p)
164 {
165 cmp_result = CmpLess;
166 p = LLINK(p);
167 }
168 else // key >= KEY(p), could be equal
169 {
170 candidate = p;
171 candidate_pos = path.size();
172 cmp_result = CmpGreater;
173 p = RLINK(p);
174 }
175 }
176 while (p != Node::NullPtr);
177
178 // Optimistic duplicate check: when going right, key >= KEY(candidate)
179 // If also KEY(candidate) >= key (i.e., not less), then key == KEY(candidate)
180 if (candidate != nullptr and not static_cast<bool>(cmp(KEY(candidate), key))) [[unlikely]]
181 {
182 cmp_result = CmpEqual;
183 // Truncate stack: remove nodes pushed after candidate
184 const size_t to_pop =
185 path.size() > candidate_pos ?
186 path.size() - candidate_pos : 0;
187 if (to_pop > 0)
188 path.popn(to_pop);
189 return candidate;
190 }
191
192 return path.top();
193 }
194
197 Node * search_dup_and_stack_rb(const Key & key,
198 signed char & cmp_result, Path & path)
199 noexcept(nothrow_compare_v<Compare, Key>)
200 {
201 Node *p = root;
202 path.push(head);
203 cmp_result = CmpEqual;
204 do
205 {
206 path.push(p);
207 const Key & pk = KEY(p);
208 if (cmp(key, pk))
209 {
210 cmp_result = CmpLess;
211 p = LLINK(p);
212 }
213 else
214 {
215 cmp_result = CmpGreater;
216 p = RLINK(p);
217 }
218 }
219 while (p != Node::NullPtr);
220
221 return path.top();
222 }
223
225 void fix_red_condition(Node *p, Path & path) noexcept
226 {
227 assert(COLOR(p) == RED);
228
229 while (p != root)
230 {
231 Node *pp = path.pop(); // parent of p
232 if (COLOR(pp) == BLACK) // is p's parent black?
233 break; // yes ==> no consecutive reds ==> done
234
235 if (root == pp) // is p a direct child of the root?
236 {
237 COLOR(root) = BLACK;
238 break;
239 }
240
241 Node *ppp = path.pop(); // grandparent of p
242 Node *spp = LLINK(ppp) == pp ? RLINK(ppp) : LLINK(ppp); // uncle
243
244 if (COLOR(spp) == RED) // is p's uncle red?
245 {
246 COLOR(ppp) = RED;
247 COLOR(pp) = BLACK;
248 COLOR(spp) = BLACK;
249 p = ppp;
250 continue;
251 }
252
253 Node *pppp = path.pop(); // great-grandparent of p
254 if (LLINK(pp) == p and LLINK(ppp) == pp)
255 {
256 rotate_to_right(ppp, pppp);
257 COLOR(pp) = BLACK;
258 }
259 else if (RLINK(pp) == p and RLINK(ppp) == pp)
260 {
261 rotate_to_left(ppp, pppp);
262 COLOR(pp) = BLACK;
263 }
264 else
265 {
266 if (RLINK(pp) == p)
267 {
268 rotate_to_left(pp, ppp);
269 rotate_to_right(ppp, pppp);
270 }
271 else
272 {
273 rotate_to_right(pp, ppp);
274 rotate_to_left(ppp, pppp);
275 }
276 COLOR(p) = BLACK;
277 }
278
279 COLOR(ppp) = RED;
280 break;
281 }
282 }
283
285 void find_succ_and_swap(Node *p, Node *& pp, Path & path) noexcept
286 {
287 Node *& ref_path_top = path.top();
288
289 Node *fSucc = p;
290 Node *succ = RLINK(p);
291 path.push(succ);
292
293 while (LLINK(succ) != Node::NullPtr)
294 {
295 fSucc = succ;
296 succ = LLINK(succ);
297 path.push(succ);
298 }
299
300 ref_path_top = succ;
301 path.top() = p;
302
303 if (LLINK(pp) == p)
304 LLINK(pp) = succ;
305 else
306 RLINK(pp) = succ;
307
308 LLINK(succ) = LLINK(p);
309 LLINK(p) = Node::NullPtr;
310
311 if (RLINK(p) == succ)
312 {
313 RLINK(p) = RLINK(succ);
314 RLINK(succ) = p;
315 pp = succ;
316 }
317 else
318 {
319 Node *succr = RLINK(succ);
320 RLINK(succ) = RLINK(p);
321 LLINK(fSucc) = p;
322 RLINK(p) = succr;
323 pp = fSucc;
324 }
325
326 std::swap(COLOR(succ), COLOR(p));
327 }
328
330 void fix_black_condition(Node *p, Path & path) noexcept
331 {
332 if (COLOR(p) == RED)
333 {
334 COLOR(p) = BLACK;
335 return;
336 }
337
338 Node *pp = path.popn(2);
339 while (p != root)
340 {
341 assert(LLINK(pp) == p or RLINK(pp) == p);
342 assert(LLINK(path.top()) == pp or RLINK(path.top()) == pp);
343
344 Node *sp = LLINK(pp) == p ? RLINK(pp) : LLINK(pp);
345 if (COLOR(sp) == RED)
346 {
347 Node *& ppp = path.top();
348
349 if (LLINK(pp) == p)
350 {
351 sp = LLINK(sp);
352 ppp = rotate_to_left(pp, ppp);
353 }
354 else
355 {
356 sp = RLINK(sp);
357 ppp = rotate_to_right(pp, ppp);
358 }
359
360 COLOR(ppp) = BLACK;
361 COLOR(pp) = RED;
362 }
363
364 Node *np, *snp;
365 if (LLINK(pp) == p)
366 {
367 np = RLINK(sp);
368 snp = LLINK(sp);
369 }
370 else
371 {
372 np = LLINK(sp);
373 snp = RLINK(sp);
374 }
375
376 if (COLOR(np) == RED)
377 {
378 Node *ppp = path.top();
379
380 if (RLINK(sp) == np)
381 rotate_to_left(pp, ppp);
382 else
383 rotate_to_right(pp, ppp);
384
385 COLOR(sp) = COLOR(pp);
386 COLOR(pp) = BLACK;
387 COLOR(np) = BLACK;
388
389 return;
390 }
391
392 if (COLOR(snp) == RED)
393 {
394 Node *ppp = path.top();
395
396 if (LLINK(sp) == snp)
397 {
398 rotate_to_right(sp, pp);
399 rotate_to_left(pp, ppp);
400 }
401 else
402 {
403 rotate_to_left(sp, pp);
404 rotate_to_right(pp, ppp);
405 }
406
407 COLOR(snp) = COLOR(pp);
408 COLOR(pp) = BLACK;
409
410 return;
411 }
412
413 if (COLOR(pp) == RED)
414 {
415 COLOR(pp) = BLACK;
416 COLOR(sp) = RED;
417 return;
418 }
419
420 COLOR(sp) = RED;
421 p = pp;
422 pp = path.pop();
423 }
424 }
425
427 void init() noexcept
428 {
429 num_nodes = 0;
430 }
431
432public:
434 Compare & key_comp() noexcept { return cmp; }
435 const Compare & key_comp() const noexcept { return cmp; }
436
438 Compare & get_compare() noexcept { return cmp; }
439 const Compare & get_compare() const noexcept { return cmp; }
440
455 noexcept(std::is_nothrow_default_constructible_v<Node> and
456 std::is_nothrow_default_constructible_v<Compare> and
457 std::is_nothrow_constructible_v<Compare, Compare &>)
458 : Gen_Rb_Tree(Compare())
459 {
460 // empty
461 }
462
471 Gen_Rb_Tree(Compare __cmp)
472 noexcept(std::is_nothrow_default_constructible_v<Node> and
473 std::is_nothrow_constructible_v<Compare, Compare &>)
474 : head(&head_node), root(head_node.getR()),
475 cmp(__cmp), num_nodes(0)
476 {
477 /* empty */
478 }
479
485 void swap(Gen_Rb_Tree & tree) noexcept(std::is_nothrow_swappable_v<Compare>)
486 {
487 // The comparison first: if its swap throws, the nodes stay where
488 // they were
489 std::swap(cmp, tree.cmp);
490 std::swap(root, tree.root);
491 std::swap(num_nodes, tree.num_nodes);
492 }
493
512 noexcept(bin_node_detail::nothrow_header_from_v<Node> and
513 bin_node_detail::nothrow_compare_taken_v<Compare>)
514 : head_node(bin_node_detail::header_from(tree.head_node)),
515 head(&head_node), root(head_node.getR()),
516 cmp(bin_node_detail::compare_to_take(tree.cmp)),
517 num_nodes(tree.num_nodes)
518 {
519 root = tree.root;
520 tree.root = Node::NullPtr;
521 tree.num_nodes = 0;
522 }
523
532 noexcept(std::is_nothrow_move_assignable_v<Compare>)
533 {
534 if (this != &tree)
535 {
536 // The comparison first: if its move throws, no tree has changed
537 cmp = std::move(tree.cmp);
538 root = tree.root;
539 num_nodes = tree.num_nodes;
540 tree.root = Node::NullPtr;
541 tree.num_nodes = 0;
542 }
543 return *this;
544 }
545
547 virtual ~Gen_Rb_Tree() = default;
548
557 Node * search(const Key & key) const noexcept(nothrow_compare_v<Compare, Key>)
558 {
559 Node *p = root;
560 while (p != Node::NullPtr)
561 {
562 if (cmp(key, KEY(p)))
563 p = LLINK(p);
564 else if (cmp(KEY(p), key))
565 p = RLINK(p);
566 else
567 return p;
568 }
569 return nullptr;
570 }
571
573 Node *& getRoot() noexcept { return root; }
574
576 Node * getRoot() const noexcept { return root; }
577
579 bool is_empty() const noexcept { return root == Node::NullPtr; }
580
582 size_t size() const noexcept { return num_nodes; }
583
585 void reset() noexcept
586 {
587 root = Node::NullPtr;
588 num_nodes = 0;
589 }
590
600 Node * insert(Node *p) noexcept(nothrow_compare_v<Compare, Key>)
601 {
602 assert(p != nullptr and p != Node::NullPtr);
603 assert(COLOR(p) == RED);
604
605 if (root == Node::NullPtr)
606 {
607 ++num_nodes;
608 return root = p;
609 }
610
611 signed char cmp_result = CmpEqual;
612 Path path;
613 Node *q = search_and_stack_rb(KEY(p), cmp_result, path);
614 if (cmp_result == CmpLess)
615 LLINK(q) = p;
616 else if (cmp_result == CmpGreater)
617 RLINK(q) = p;
618 else
619 return nullptr; // duplicate key
620
621 ++num_nodes;
622 fix_red_condition(p, path);
623
624 return p;
625 }
626
636 Node * search_or_insert(Node *p) noexcept(nothrow_compare_v<Compare, Key>)
637 {
638 assert(p != nullptr and p != Node::NullPtr);
639 assert(COLOR(p) == RED);
640
641 if (root == Node::NullPtr)
642 {
643 ++num_nodes;
644 return root = p;
645 }
646
647 signed char cmp_result = CmpEqual;
648 Path path;
649 Node *q = search_and_stack_rb(KEY(p), cmp_result, path);
650 if (cmp_result == CmpLess)
651 LLINK(q) = p;
652 else if (cmp_result == CmpGreater)
653 RLINK(q) = p;
654 else
655 return q; // return existing node
656
657 ++num_nodes;
658 fix_red_condition(p, path);
659
660 return p;
661 }
662
672 Node * insert_dup(Node *p) noexcept(nothrow_compare_v<Compare, Key>)
673 {
674 assert(p != nullptr and p != Node::NullPtr);
675 assert(COLOR(p) == RED);
676
677 if (root == Node::NullPtr)
678 {
679 ++num_nodes;
680 return root = p;
681 }
682
683 signed char cmp_result = CmpEqual;
684 Path path;
685 Node *q = search_dup_and_stack_rb(KEY(p), cmp_result, path);
686 if (cmp_result == CmpLess)
687 LLINK(q) = p;
688 else
689 RLINK(q) = p;
690
691 ++num_nodes;
692 fix_red_condition(p, path);
693
694 return p;
695 }
696
699 bool verify() const { return is_red_black_bst(root, cmp); }
700
710 Node * remove(const Key & key) noexcept(nothrow_compare_v<Compare, Key>)
711 {
712 if (root == Node::NullPtr)
713 return nullptr;
714
715 signed char cmp_result = CmpEqual;
716 Path path;
717 Node *q = search_and_stack_rb(key, cmp_result, path);
718 if (cmp_result != CmpEqual)
719 return nullptr;
720
721 Node *pq = path.top(1);
722 Node *p;
723 while (true)
724 {
725 if (LLINK(q) == Node::NullPtr)
726 {
727 if (LLINK(pq) == q)
728 p = LLINK(pq) = RLINK(q);
729 else
730 p = RLINK(pq) = RLINK(q);
731 break;
732 }
733
734 if (RLINK(q) == Node::NullPtr)
735 {
736 if (LLINK(pq) == q)
737 p = LLINK(pq) = LLINK(q);
738 else
739 p = RLINK(pq) = LLINK(q);
740 break;
741 }
742
743 find_succ_and_swap(q, pq, path);
744 }
745
746 if (COLOR(q) == BLACK)
747 fix_black_condition(p, path);
748
749 q->reset();
750 --num_nodes;
751
752 return q;
753 }
754
761 struct Iterator : public BinNodeInfixIterator<Node>
762 {
764 Iterator() noexcept = default;
767 };
768};
769
777template <typename Key, class Compare = Aleph::less<Key>>
778 requires StrictWeakOrder<Compare, Key>
779struct Rb_Tree : public Gen_Rb_Tree<RbNode, Key, Compare>
780{
782 using Base::Base;
783};
784
792template <typename Key, class Compare = Aleph::less<Key>>
794struct Rb_Tree_Vtl : public Gen_Rb_Tree<RbNodeVtl, Key, Compare>
795{
797 using Base::Base;
798};
799
800} // end namespace Aleph
801
802# endif // TPL_RB_TREE_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Standard functor implementations and comparison objects.
@ KEY
Definition btreepic.C:169
Inorder iterator on the nodes of a binary tree.
Red-black binary search tree implementation (bottom-up).
const Compare & get_compare() const noexcept
Node * insert_dup(Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Insert a node allowing duplicates.
void reset() noexcept
Reset tree to empty state (does not free nodes)
void fix_red_condition(Node *p, Path &path) noexcept
Fix red-red violation after insertion.
Node * search_dup_and_stack_rb(const Key &key, signed char &cmp_result, Path &path) noexcept(nothrow_compare_v< Compare, Key >)
Search for insertion point (allows duplicates) and stack ancestors.
Node * search(const Key &key) const noexcept(nothrow_compare_v< Compare, Key >)
Search for a key in the tree.
void fix_black_condition(Node *p, Path &path) noexcept
Fix black-height violation after deletion.
void find_succ_and_swap(Node *p, Node *&pp, Path &path) noexcept
Find successor and swap with node being deleted.
Gen_Rb_Tree(Compare __cmp) noexcept(std::is_nothrow_default_constructible_v< Node > and std::is_nothrow_constructible_v< Compare, Compare & >)
Builds an empty tree with the comparison criteria __cmp.
Node * remove(const Key &key) noexcept(nothrow_compare_v< Compare, Key >)
Remove the node containing key.
const Compare & key_comp() const noexcept
size_t num_nodes
Number of nodes in tree.
Gen_Rb_Tree(Gen_Rb_Tree &&tree) noexcept(bin_node_detail::nothrow_header_from_v< Node > and bin_node_detail::nothrow_compare_taken_v< Compare >)
Takes the nodes and the comparison criteria of tree, which is left empty and can take nodes again.
Node * search_and_stack_rb(const Key &key, signed char &cmp_result, Path &path) noexcept(nothrow_compare_v< Compare, Key >)
Search for key and stack ancestors (optimistic duplicate detection).
Node *& root
Reference to root (right child of head)
Compare cmp
Comparison functor.
void swap(Gen_Rb_Tree &tree) noexcept(std::is_nothrow_swappable_v< Compare >)
Swaps all elements with another tree in constant time.
Node * getRoot() const noexcept
Get const root pointer.
virtual ~Gen_Rb_Tree()=default
Destructor.
NodeType< Key > Node
size_t size() const noexcept
Returns the number of nodes in the tree (O(1))
Node * head
Pointer to sentinel.
Node * insert(Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Insert a node into the tree.
Node head_node
Sentinel header node.
Compare & get_compare() noexcept
See key_comp().
bool verify() const
Verify that tree satisfies red-black properties and that its keys are in order.
Node *& getRoot() noexcept
Get reference to root pointer.
Gen_Rb_Tree & operator=(Gen_Rb_Tree &&tree) noexcept(std::is_nothrow_move_assignable_v< Compare >)
Takes the nodes and the comparison criteria of tree, which is left empty.
bool is_empty() const noexcept
Returns true if the tree is empty.
Compare & key_comp() noexcept
Returns a reference to the comparison criteria.
static constexpr signed char CmpEqual
Gen_Rb_Tree() noexcept(std::is_nothrow_default_constructible_v< Node > and std::is_nothrow_default_constructible_v< Compare > and std::is_nothrow_constructible_v< Compare, Compare & >)
Builds an empty tree with a comparison criteria built by default.
void init() noexcept
Initialize tree state.
static constexpr signed char CmpLess
static constexpr signed char CmpGreater
Node * search_or_insert(Node *p) noexcept(nothrow_compare_v< Compare, Key >)
Search for key or insert if not found.
Stack of fixed capacity whose storage is inside the object.
T & top() noexcept
Return a modifiable reference to the top; the stack must not be empty.
Strict weak ordering constraint for BST comparators.
Node * rotate_to_left(Node *p) noexcept
Rotate to the left the tree with root p
Node * rotate_to_right(Node *p) noexcept
Rotate to the right the tree with root p
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
#define COLOR(p)
Definition quadnode.H:59
Red-Black tree node definition and validation utilities.
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
#define BLACK
Black color constant.
Definition rbNode.H:80
#define RED
Red color constant (newly inserted nodes are red)
Definition rbNode.H:77
Iterator over tree nodes in sorted order.
Iterator() noexcept=default
Default constructor creates an "end" iterator.
Iterator(const Gen_Rb_Tree &t)
Red-black tree with virtual destructor in nodes.
Red-black tree with nodes without virtual destructor.
#define RLINK(i, n)
#define LLINK(i, n)
Stack implementations backed by dynamic or fixed arrays.
Utility functions for binary tree operations.