---
name: "tree"
section: "3bsd"
platform: "linux"
package: "libbsd"
version: "0.12.2-2"
release: "Arch Linux 2026-11-01"
platforms: ["linux"]
url: "https://new.carta.tech/tree/3bsd"
---

# tree(3bsd)

implementations of splay and red-black trees

## NAME

**SPLAY\_PROTOTYPE**, **SPLAY\_GENERATE**, **SPLAY\_ENTRY**, **SPLAY\_HEAD**, **SPLAY\_INITIALIZER**, **SPLAY\_ROOT**, **SPLAY\_EMPTY**, **SPLAY\_NEXT**, **SPLAY\_MIN**, **SPLAY\_MAX**, **SPLAY\_FIND**, **SPLAY\_LEFT**, **SPLAY\_RIGHT**, **SPLAY\_FOREACH**, **SPLAY\_INIT**, **SPLAY\_INSERT**, **SPLAY\_REMOVE**, **RB\_PROTOTYPE**, **RB\_PROTOTYPE\_STATIC**, **RB\_GENERATE**, **RB\_GENERATE\_STATIC**, **RB\_ENTRY**, **RB\_HEAD**, **RB\_INITIALIZER**, **RB\_ROOT**, **RB\_EMPTY**, **RB\_NEXT**, **RB\_PREV**, **RB\_MIN**, **RB\_MAX**, **RB\_FIND**, **RB\_NFIND**, **RB\_LEFT**, **RB\_RIGHT**, **RB\_PARENT**, **RB\_FOREACH**, **RB\_FOREACH\_SAFE**, **RB\_FOREACH\_REVERSE**, **RB\_FOREACH\_REVERSE\_SAFE**, **RB\_INIT**, **RB\_INSERT**, **RB\_REMOVE** – implementations of splay and red-black trees

## LIBRARY

library “libbsd”

## SYNOPSIS

**#include \<sys/tree.h\>**

(See [libbsd(7)](/libbsd/7.md) for include usage.)

**SPLAY\_PROTOTYPE**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**SPLAY\_GENERATE**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**SPLAY\_ENTRY**(*TYPE*);

**SPLAY\_HEAD**(*HEADNAME*, *TYPE*);

*struct TYPE \**\

**SPLAY\_INITIALIZER**(*SPLAY\_HEAD \*head*);

**SPLAY\_ROOT**(*SPLAY\_HEAD \*head*);

*int*\

**SPLAY\_EMPTY**(*SPLAY\_HEAD \*head*);

*struct TYPE \**\

**SPLAY\_NEXT**(*NAME*, *SPLAY\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**SPLAY\_MIN**(*NAME*, *SPLAY\_HEAD \*head*);

*struct TYPE \**\

**SPLAY\_MAX**(*NAME*, *SPLAY\_HEAD \*head*);

*struct TYPE \**\

**SPLAY\_FIND**(*NAME*, *SPLAY\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**SPLAY\_LEFT**(*struct TYPE \*elm*, *SPLAY\_ENTRY NAME*);

*struct TYPE \**\

**SPLAY\_RIGHT**(*struct TYPE \*elm*, *SPLAY\_ENTRY NAME*);

**SPLAY\_FOREACH**(*VARNAME*, *NAME*, *SPLAY\_HEAD \*head*);

*void*\

**SPLAY\_INIT**(*SPLAY\_HEAD \*head*);

*struct TYPE \**\

**SPLAY\_INSERT**(*NAME*, *SPLAY\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**SPLAY\_REMOVE**(*NAME*, *SPLAY\_HEAD \*head*, *struct TYPE \*elm*);

**RB\_PROTOTYPE**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**RB\_PROTOTYPE\_STATIC**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**RB\_GENERATE**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**RB\_GENERATE\_STATIC**(*NAME*, *TYPE*, *FIELD*, *CMP*);

**RB\_ENTRY**(*TYPE*);

**RB\_HEAD**(*HEADNAME*, *TYPE*);

**RB\_INITIALIZER**(*RB\_HEAD \*head*);

*struct TYPE \**\

**RB\_ROOT**(*RB\_HEAD \*head*);

*int*\

**RB\_EMPTY**(*RB\_HEAD \*head*);

*struct TYPE \**\

**RB\_NEXT**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**RB\_PREV**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**RB\_MIN**(*NAME*, *RB\_HEAD \*head*);

*struct TYPE \**\

**RB\_MAX**(*NAME*, *RB\_HEAD \*head*);

*struct TYPE \**\

**RB\_FIND**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**RB\_NFIND**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**RB\_LEFT**(*struct TYPE \*elm*, *RB\_ENTRY NAME*);

*struct TYPE \**\

**RB\_RIGHT**(*struct TYPE \*elm*, *RB\_ENTRY NAME*);

*struct TYPE \**\

**RB\_PARENT**(*struct TYPE \*elm*, *RB\_ENTRY NAME*);

**RB\_FOREACH**(*VARNAME*, *NAME*, *RB\_HEAD \*head*);

**RB\_FOREACH\_SAFE**(*VARNAME*, *NAME*, *RB\_HEAD \*head*, *TEMP\_VARNAME*);

**RB\_FOREACH\_REVERSE**(*VARNAME*, *NAME*, *RB\_HEAD \*head*);

**RB\_FOREACH\_REVERSE\_SAFE**(*VARNAME*, *NAME*, *RB\_HEAD \*head*, *TEMP\_VARNAME*);

*void*\

**RB\_INIT**(*RB\_HEAD \*head*);

*struct TYPE \**\

**RB\_INSERT**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

*struct TYPE \**\

**RB\_REMOVE**(*NAME*, *RB\_HEAD \*head*, *struct TYPE \*elm*);

## DESCRIPTION

These macros define data structures for different types of trees: splay trees and red-black trees.

In the macro definitions, *TYPE* is the name tag of a user defined structure that must contain a field named *FIELD*, of type SPLAY\_ENTRY or RB\_ENTRY. The argument *HEADNAME* is the name tag of a user defined structure that must be declared using the macros **SPLAY\_HEAD**() or **RB\_HEAD**(). The argument *NAME* has to be a unique name prefix for every tree that is defined.

The function prototypes are declared with SPLAY\_PROTOTYPE, RB\_PROTOTYPE, or RB\_PROTOTYPE\_STATIC. The function bodies are generated with SPLAY\_GENERATE, RB\_GENERATE, or RB\_GENERATE\_STATIC. See the examples below for further explanation of how these macros are used.

## SPLAY TREES

A splay tree is a self-organizing data structure. Every operation on the tree causes a splay to happen. The splay moves the requested node to the root of the tree and partly rebalances it.

This has the benefit that request locality causes faster lookups as the requested nodes move to the top of the tree. On the other hand, every lookup causes memory writes.

The Balance Theorem bounds the total access time for m operations and n inserts on an initially empty tree as O((m + n)lg n). The amortized cost for a sequence of m accesses to a splay tree is O(lg n).

A splay tree is headed by a structure defined by the **SPLAY\_HEAD**() macro. A *SPLAY\_HEAD* structure is declared as follows:

```
SPLAY_HEAD(HEADNAME, TYPE) head;
```

where *HEADNAME* is the name of the structure to be defined, and struct *TYPE* is the type of the elements to be inserted into the tree.

The **SPLAY\_ENTRY**() macro declares a structure that allows elements to be connected in the tree.

In order to use the functions that manipulate the tree structure, their prototypes need to be declared with the **SPLAY\_PROTOTYPE**() macro, where *NAME* is a unique identifier for this particular tree. The *TYPE* argument is the type of the structure that is being managed by the tree. The *FIELD* argument is the name of the element defined by **SPLAY\_ENTRY**().

The function bodies are generated with the **SPLAY\_GENERATE**() macro. It takes the same arguments as the **SPLAY\_PROTOTYPE**() macro, but should be used only once.

Finally, the *CMP* argument is the name of a function used to compare trees' nodes with each other. The function takes two arguments of type *struct TYPE \**. If the first argument is smaller than the second, the function returns a value smaller than zero. If they are equal, the function returns zero. Otherwise, it should return a value greater than zero. The compare function defines the order of the tree elements.

The **SPLAY\_INIT**() macro initializes the tree referenced by *head*.

The splay tree can also be initialized statically by using the **SPLAY\_INITIALIZER**() macro like this:

```
SPLAY_HEAD(HEADNAME, TYPE) head = SPLAY_INITIALIZER(&head);
```

The **SPLAY\_INSERT**() macro inserts the new element *elm* into the tree. Upon success, *NULL* is returned. If a matching element already exists in the tree, the insertion is aborted, and a pointer to the existing element is returned.

The **SPLAY\_REMOVE**() macro removes the element *elm* from the tree pointed by *head*. Upon success, a pointer to the removed element is returned. *NULL* is returned if *elm* is not present in the tree.

The **SPLAY\_FIND**() macro can be used to find a particular element in the tree.

```
struct TYPE find, *res;
find.key = 30;
res = SPLAY_FIND(NAME, &head, &find);
```

The **SPLAY\_ROOT**(), **SPLAY\_MIN**(), **SPLAY\_MAX**(), and **SPLAY\_NEXT**() macros can be used to traverse the tree:

```
for (np = SPLAY_MIN(NAME, &head); np != NULL; np = SPLAY_NEXT(NAME, &head, np))
```

Or, for simplicity, one can use the **SPLAY\_FOREACH**() macro:

```
SPLAY_FOREACH(np, NAME, &head)
```

The **SPLAY\_EMPTY**() macro should be used to check whether a splay tree is empty.

## RED-BLACK TREES

A red-black tree is a binary search tree with the node color as an extra attribute. It fulfills a set of conditions:

1. every search path from the root to a leaf consists of the same number of black nodes,

2. each red node (except for the root) has a black parent,

3. each leaf node is black.

Every operation on a red-black tree is bounded as O(lg n). The maximum height of a red-black tree is 2lg (n+1).

A red-black tree is headed by a structure defined by the **RB\_HEAD**() macro. A *RB\_HEAD* structure is declared as follows:

```
RB_HEAD(HEADNAME, TYPE) head;
```

where *HEADNAME* is the name of the structure to be defined, and struct *TYPE* is the type of the elements to be inserted into the tree.

The **RB\_ENTRY**() macro declares a structure that allows elements to be connected in the tree.

In order to use the functions that manipulate the tree structure, their prototypes need to be declared with the **RB\_PROTOTYPE**() or **RB\_PROTOTYPE\_STATIC**() macros, where *NAME* is a unique identifier for this particular tree. The *TYPE* argument is the type of the structure that is being managed by the tree. The *FIELD* argument is the name of the element defined by **RB\_ENTRY**().

The function bodies are generated with the **RB\_GENERATE**() or **RB\_GENERATE\_STATIC**() macros. These macros take the same arguments as the **RB\_PROTOTYPE**() and **RB\_PROTOTYPE\_STATIC**() macros, but should be used only once.

Finally, the *CMP* argument is the name of a function used to compare trees' nodes with each other. The function takes two arguments of type *struct TYPE \**. If the first argument is smaller than the second, the function returns a value smaller than zero. If they are equal, the function returns zero. Otherwise, it should return a value greater than zero. The compare function defines the order of the tree elements.

The **RB\_INIT**() macro initializes the tree referenced by *head*.

The red-black tree can also be initialized statically by using the **RB\_INITIALIZER**() macro like this:

```
RB_HEAD(HEADNAME, TYPE) head = RB_INITIALIZER(&head);
```

The **RB\_INSERT**() macro inserts the new element *elm* into the tree. Upon success, *NULL* is returned. If a matching element already exists in the tree, the insertion is aborted, and a pointer to the existing element is returned.

The **RB\_REMOVE**() macro removes the element *elm* from the tree pointed by *head*. **RB\_REMOVE**() returns *elm*.

The **RB\_FIND**() and **RB\_NFIND**() macros can be used to find a particular element in the tree. **RB\_FIND**() finds the node with the same key as *elm*. **RB\_NFIND**() finds the first node greater than or equal to the search key.

```
struct TYPE find, *res;
find.key = 30;
res = RB_FIND(NAME, &head, &find);
```

The **RB\_ROOT**(), **RB\_MIN**(), **RB\_MAX**(), **RB\_NEXT**(), and **RB\_PREV**() macros can be used to traverse the tree:

```
for (np = RB_MIN(NAME, &head); np != NULL; np = RB_NEXT(NAME, &head, np))
```

Or, for simplicity, one can use the **RB\_FOREACH**() or **RB\_FOREACH\_REVERSE**() macros:

```
RB_FOREACH(np, NAME, &head)
```

The macros **RB\_FOREACH\_SAFE**() and **RB\_FOREACH\_REVERSE\_SAFE**() traverse the tree referenced by head in a forward or reverse direction respectively, assigning each element in turn to np. However, unlike their unsafe counterparts, they permit both the removal of np as well as freeing it from within the loop safely without interfering with the traversal.

The **RB\_EMPTY**() macro should be used to check whether a red-black tree is empty.

## EXAMPLES

The following example demonstrates how to declare a red-black tree holding integers. Values are inserted into it and the contents of the tree are printed in order. Lastly, the internal structure of the tree is printed.

```
#include <sys/tree.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
struct node {
	RB_ENTRY(node) entry;
	int i;
};
int	intcmp(struct node *, struct node *);
void	print_tree(struct node *);
int
intcmp(struct node *e1, struct node *e2)
{
	return (e1->i < e2->i ? -1 : e1->i > e2->i);
}
RB_HEAD(inttree, node) head = RB_INITIALIZER(&head);
RB_PROTOTYPE(inttree, node, entry, intcmp)
RB_GENERATE(inttree, node, entry, intcmp)
int testdata[] = {
	20, 16, 17, 13, 3, 6, 1, 8, 2, 4, 10, 19, 5, 9, 12, 15, 18,
	7, 11, 14
};
void
print_tree(struct node *n)
{
	struct node *left, *right;
	if (n == NULL) {
		printf("nil");
		return;
	}
	left = RB_LEFT(n, entry);
	right = RB_RIGHT(n, entry);
	if (left == NULL && right == NULL)
		printf("%d", n->i);
	else {
		printf("%d(", n->i);
		print_tree(left);
		printf(",");
		print_tree(right);
		printf(")");
	}
}
int
main(void)
{
	int i;
	struct node *n;
	for (i = 0; i < sizeof(testdata) / sizeof(testdata[0]); i++) {
		if ((n = malloc(sizeof(struct node))) == NULL)
			err(1, NULL);
		n->i = testdata[i];
		RB_INSERT(inttree, &head, n);
	}
	RB_FOREACH(n, inttree, &head) {
		printf("%d\n", n->i);
	}
	print_tree(RB_ROOT(&head));
	printf("\n");
	return (0);
}
```

## SEE ALSO

[queue(3bsd)](/queue/3bsd.md)

## HISTORY

The tree macros first appeared in FreeBSD 4.6.

## NOTES

Trying to free a tree in the following way is a common error:

```
SPLAY_FOREACH(var, NAME, &head) {
	SPLAY_REMOVE(NAME, &head, var);
	free(var);
}
free(head);
```

Since *var* is free'd, the **FOREACH**() macro refers to a pointer that may have been reallocated already. Proper code needs a second variable.

```
for (var = SPLAY_MIN(NAME, &head); var != NULL; var = nxt) {
	nxt = SPLAY_NEXT(NAME, &head, var);
	SPLAY_REMOVE(NAME, &head, var);
	free(var);
}
```

## AUTHORS

The author of the tree macros is Niels Provos.
