001 红黑树(二)之 C语言的实现(3)

时间:2022-06-24
本文章向大家介绍001 红黑树(二)之 C语言的实现(3),主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

红黑树的测试文件(rbtree_test.c):

 1/**
 2 * C语言实现的红黑树(Red Black Tree)
 3 *
 4 * @author skywang
 5 * @date 2013/11/18
 6 */
 7#include <stdio.h>
 8#include "rbtree.h"
 9#define CHECK_INSERT 0    // "插入"动作的检测开关(0,关闭;1,打开)
10#define CHECK_DELETE 0    // "删除"动作的检测开关(0,关闭;1,打开)
11#define LENGTH(a) ( (sizeof(a)) / (sizeof(a[0])) )
12void main()
13{
14    int a[] = {10, 40, 30, 60, 90, 70, 20, 50, 80};
15    int i, ilen=LENGTH(a);
16    RBRoot *root=NULL;
17    root = create_rbtree();
18    printf("== 原始数据: ");
19    for(i=0; i<ilen; i++)
20        printf("%d ", a[i]);
21    printf("n");
22    for(i=0; i<ilen; i++)
23    {
24        insert_rbtree(root, a[i]);
25#if CHECK_INSERT
26        printf("== 添加节点: %dn", a[i]);
27        printf("== 树的详细信息: n");
28        print_rbtree(root);
29        printf("n");
30#endif
31    }
32    printf("== 前序遍历: ");
33    preorder_rbtree(root);
34    printf("n== 中序遍历: ");
35    inorder_rbtree(root);
36    printf("n== 后序遍历: ");
37    postorder_rbtree(root);
38    printf("n");
39    if (rbtree_minimum(root, &i)==0)
40        printf("== 最小值: %dn", i);
41    if (rbtree_maximum(root, &i)==0)
42        printf("== 最大值: %dn", i);
43    printf("== 树的详细信息: n");
44    print_rbtree(root);
45    printf("n");
46#if CHECK_DELETE
47    for(i=0; i<ilen; i++)
48    {
49        delete_rbtree(root, a[i]);
50        printf("== 删除节点: %dn", a[i]);
51        if (root)
52        {
53            printf("== 树的详细信息: n");
54            print_rbtree(root);
55            printf("n");
56        }
57    }
58#endif
59    destroy_rbtree(root);
60}

红黑树的C测试程序

前面已经给出了红黑树的测试程序(rbtree_test.c),这里就不再重复说明。下面是测试程序的运行结果:

 1== 原始数据: 10 40 30 60 90 70 20 50 80 
 2== 前序遍历: 30 10 20 60 40 50 80 70 90 
 3== 中序遍历: 10 20 30 40 50 60 70 80 90 
 4== 后序遍历: 20 10 50 40 70 90 80 60 30 
 5== 最小值: 10
 6== 最大值: 90
 7== 树的详细信息: 
 830(B) is root
 910(B) is 30's   left child
1020(R) is 10's  right child
1160(R) is 30's  right child
1240(B) is 60's   left child
1350(R) is 40's  right child
1480(B) is 60's  right child
1570(R) is 80's   left child
1690(R) is 80's  right child

文章来源: http://www.cnblogs.com/skywang12345/p/3624177.html

欢迎关注公众号『easyserverdev』。如果有任何技术或者职业方面的问题需要我提供帮助,可通过这个公众号与我取得联系,同时,您也可以加入我的QQ群578019391。此公众号不仅分享高性能服务器开发经验和故事,同时也免费为广大技术朋友提供技术答疑和职业解惑,您有任何问题都可以在微信公众号直接留言或到群里提问,我会尽快回复您。