Macro RBTREE_DECL_STRUCTS(Name, Node, K, T) is used to declare a Red-Black tree struct and node struct.
Name: Name of the main tree struct.
Node: Name of the tree node struct.
K: Key type.
T: Value type.
Macro RBTREE_IMPL(Name, Node, K, T, Mods...) is used to define the Red-Black tree functions.
Name: Name of the main tree struct.
Node: Name of the tree node struct.
K: Key type.
T: Value type.
Mods: Optional modifiers to apply to before function definitions,
like static can be used to keep the tree functions local to a file.
Macro RBTREE_DECL_FUNCTIONS(Name, Node, K, T) is used to forward-declare the functions.
Code Example
#include"rb_tree.h"#include"rb_tree_def.h"#include<stdio.h>#include<stdlib.h>typedefstruct {
intmy_int;
} Data;
RBTREE_DECL_STRUCTS(RBTree, Node, int, int)
RBTREE_IMPL(RBTree, Node, int, int)
intmain() {
RBTreetree=RBTree_new();
// New nodes can be allocated however you likeNode*node=malloc(sizeof(Node));
// Inserting a new value into the treeRBTree_insert(&tree, 0, (Data) {10}, node);
// Getting the height of the treeintmax_theight=RBTree_height(&tree);
// Searching from the treeNode*searchedNode=RBTree_search(&tree, 10);
printf("%d\n", searchedNode->value);
// Getting the successor of a nodeNode*successor=RBTree_successor(&tree, searchedNode);
// Getting the predecessor of a nodeNode*predecessor=RBTree_predecessor(&tree, searchedNode);
// Deleting from the treeNode*deletedNode=RBTree_remove(&tree, searchedNode);
// deletedNode can now be freedfree(deletedNode);
}
Usage in C++
#include"rb_tree.hpp"
#include<iostream>structData {
int my_int;
};
intmain() {
RBTree<int, Data> tree;
// New nodes can be allocated anywhere you would likeauto node = new RBTree<int, Data>::Node();
// Inserting a new value into the tree
tree.insert(0, Data(10), node);
// Getting the height of the treeintmax_t height = tree.height();
// Searching from the treeauto searchedNode = tree.search(10);
std::cout << searchedNode->value << std::endl;
// Getting the successor of a nodeauto successor = tree.successor(searchedNode);
// Getting the predecessor of a nodeauto predecessor = tree.predecessor(searchedNode);
// Deleting from the treeauto deletedNode = tree.remove(searchedNode);
// deletedNode can now be freeddelete deletedNode;
}