我通过参考这篇文章和参考linux内核中的红黑树实现,总结了一下
//rbtree.h #define	RB_RED	0 #define	RB_BLACK	1 structrb_node{intval;unsignedlongrb_color;structrb_node*rb_right;structrb_node*rb_left;structrb_node*rb_parent;};structrb_root{structrb_node*rb_node;};//rbtree.c #include"rbtree.h"voidrb_set_parent(structrb_node*son,structrb_node*parent){son->rb_parent=parent;}/* * 旋转操作一共需要六步,涉及到4个节点 */voidrb_rotate_left(structrb_node*node,structrb_root*root){structrb_node*right_node=node->rb_right;structrb_node*parent_node=node->rb_parent;if((node->right=right_node->rb_left))rb_set_parent(node->right,node);right_node->rb_left=node;rb_set_parent(right_node,parent_node);if(parent_node){if(parent_node->rb_left==node){parent_node->left=right_node;}else{parent_node->right=right_node;}}else{root->rb_node=right_node;}rb_set_parent(node,right_node);}voidrb_rotate_right(structrb_node*node,structrb_root*root){structrb_node*left_node=node->rb_left;structrb_node*parent_node=node->rb_parent;if(node->rb_left=left_node->rb_right)rb_set_parent(node->rb_left,node);left_node->rb_right=node;rb_set_parent(left_node,parent_node);if(parent_node){if(parent_node->rb_left==node){parent_node->rb_left=left_node;}else{parent_node->rb_left=left_node;}}else{root->rb_node=node;}rb_set_parent(node,left_node);}voidbinaryTreeInsert(structrb_node*node,structrb_root*root){if(root->rb_node==NULL){root=node;return;}structrb_node*curr_node,*parent_node;curr_node=parent_node=root->rb_node;while(curr_node!=NULL){parent_node=curr_node;if(curr_node->val>node->val){curr_node=curr_node->rb_left;}else{curr_node=curr_node->rb_right;}}if(parent_node->val>node->val){parent_node->rb_left=node;}else{parent_node->rb_right=node;}node->rb_color=RB_RED;}