赞
踩
核心
必须保证每个节点左子树和右子树高度差值 <= 1
只有四种旋转(即四种情况)
node.right.left
) - H(node.right-right
) = 1 --> RL 旋转node.right.right
) - H(node.right-left
) = 1 --> L 旋转node.left.right
) - H(node.left-left
) = 1 --> LR 旋转node.left.left
) - H(node.left-right
) = 1 --> R 旋转算法步骤
|node.left - node.right| > 1
时,就按照上面四种情况判断,到底应该是哪种旋转。应用场景
左子树高
示例:插入 7
示例:插入 9
右子树高
示例:插入 28
示例:插入 18
核心
两条核心性质
最后一条性质确保:没有一条路径会比其他路径长出2倍。因而,红黑树是相对接近平衡的二叉树
算法核心
应用示例
右旋
左旋
case 1: 当前结点的父结点是红色且祖父结点的另一个子结点(叔叔结点)是红色。
case 2: 当前结点的父结点是红色,叔叔(假设叔叔是祖父的右子)结点是黑色,当前结点是其父结点的右子。
case 3: 当前结点的父结点是红色,叔叔(假设叔叔是祖父的右子)结点是黑色,当前结点是其父结点的左子。
int rb_insert_fixup(rb_tree_t *root, rb_node_t *node) { rb_node_t *parent; rb_node_t *grand_parent; //If parent exist, and the color of parent is RED while((parent = node->parent) && parent->color == COLOR_RED) { grand_parent = parent->parent; //parent node is grand_parent node's left child(grand_parent should not be NULL, because parent->color==COLOR_RED) if(grand_parent->left == parent) { rb_node_t *uncle = grand_parent->right; //Case 1: uncle is RED if(uncle && uncle->color == COLOR_RED) { parent->color = COLOR_BLACK; uncle->color = COLOR_BLACK; grand_parent->color = COLOR_RED; node = grand_parent; continue; } //Case 2: uncle is BLACK, and node is parent's right child if(parent->right == node) { rb_rotate_left(root, parent); // reset parent and node pointer rb_node_t *tmp; tmp = parent; parent = node; node = tmp; //Here successful convert Case 2 to Case3 } //Case 3: uncle is BLACK, and node is parent's left child parent->color = COLOR_BLACK; grand_parent->color = COLOR_RED; rb_rotate_right(root, grand_parent); } else{ rb_node_t *uncle = grand_parent->left; //Case 1: uncle is RED if(uncle && uncle->color == COLOR_RED) { parent->color = COLOR_BLACK; uncle->color = COLOR_BLACK; grand_parent->color = COLOR_RED; node = grand_parent; continue; } //Case 2: uncle is BLACK, and node is parent's left child if(parent->left == node) { rb_rotate_right(root,parent); //reset parent and node pointer rb_node_t *tmp; tmp = parent; parent = node; node = tmp; //Here success convert Case 2 to Case 3 } //Case 3: uncle is BLACK, and node is parent's right child parent->color = COLOR_BLACK; grand_parent->color = COLOR_RED; rb_rotate_left(root, grand_parent); } } (*root)->color = COLOR_BLACK; return 0x0; } int insert_rbtree(rb_tree_t *root, rb_node_t *node) { rb_node_t *p = *root; rb_node_t *q = NULL; //find the position we need to insert while(p) { q = p; if(p->key == node->key) return 1; else if(p->key > node->key) p = p->left; else p = p->right; } node->parent = q; if(q != NULL) { if(node->key < q->key) q->left = node; else q->right = node; } else{ *root = node; } node->color = COLOR_RED; return rb_insert_fixup(root, node); }
B 树相对于上面说的树,核心区别就是多叉
B+ 树的相对于 B 树的核心区别有两点
存储引擎使用 B+ 树的原因
(具体插入和删除示例可以参考我数据库的文章: 数据库索引之 B+ 树 )
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。