summaryrefslogtreecommitdiff
path: root/share/man/man3/tree.3
diff options
context:
space:
mode:
authorOtto Moerbeek <otto@cvs.openbsd.org>2005-04-16 06:11:36 +0000
committerOtto Moerbeek <otto@cvs.openbsd.org>2005-04-16 06:11:36 +0000
commitff52a23d57acf0cf0c0a58d05c282230d2c24f95 (patch)
tree4dcd9a6c6ec7a5b29d786d7207b90296c2189e1f /share/man/man3/tree.3
parentf5aaac1cb0ec066f261b5f6bf31689f4c1a3d0fe (diff)
Give a complete, working example how to use the tree macros. The
existing descripion is rather terse, and without an example it's hard to get going. ok millert@ mpech@ jmc@
Diffstat (limited to 'share/man/man3/tree.3')
-rw-r--r--share/man/man3/tree.376
1 files changed, 75 insertions, 1 deletions
diff --git a/share/man/man3/tree.3 b/share/man/man3/tree.3
index 83277efa020..889dc613230 100644
--- a/share/man/man3/tree.3
+++ b/share/man/man3/tree.3
@@ -1,4 +1,4 @@
-.\" $OpenBSD: tree.3,v 1.11 2004/02/17 19:32:13 jmc Exp $
+.\" $OpenBSD: tree.3,v 1.12 2005/04/16 06:11:35 otto Exp $
.\"/*
.\" * Copyright 2002 Niels Provos <provos@citi.umich.edu>
.\" * All rights reserved.
@@ -416,6 +416,80 @@ RB_FOREACH(np, NAME, &head)
The
.Fn RB_EMPTY
macro should be used to check whether a red-black tree is empty.
+.Sh 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.
+.Bd -literal -offset 3n
+#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 *e1, struct node *e2)
+{
+ return (e1->i - e2->i);
+}
+
+RB_HEAD(inttree, node) head = RB_INITIALIZER(&head);
+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()
+{
+ 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\en", n->i);
+ }
+ print_tree(RB_ROOT(&head));
+ printf("\en");
+ return (0);
+}
+.Ed
.Sh NOTES
Trying to free a tree in the following way is a common error:
.Bd -literal -offset indent