赞
踩
红黑树是一种含有红黑两种结点并且能够自平衡的二叉查找树。
划重点:红黑结点,自平衡,二叉查找树。
红黑树也是二叉查找树的一种,实现这一点并不难,它主要困难在自平衡的处理。
红黑树的性质:
(它在每个节点增加了一个存储位来记录节点的颜色,red或black)
(每条性质都很重要!!!)
红黑树跟AVL树不同,它不需要满足完美平衡二叉查找树
但左子树和右子树的黑结点的层数是相等的,也即任意一个节点到每个叶节点的路径都包含数量相同的黑结点,我们把红黑树这种平衡称为黑色完美平衡。
老生常谈,还是为了减小时间复杂度或者操作复杂程度。
AVL树的时间复杂度略优于红黑树,但红黑树旋转情况少于AVL树,因此插入删除操作会更加容易控制。
红黑树的整体性能略优于AVL树。
红黑树的自平衡基于三种操作:
划重点:插入节点到达正确位置之后,把插入节点定义为红色(红色结点在父结点为黑色时,红黑树的黑色平衡没被破坏)
根据以上给出的性质进行判断,代码如下:
/*judge whether the tree is a Red-Black tree*/ bool JudgeRBTree(PRBTree T) { /*empty tree is considered to be an RBtree*/ if (T == NULL) return true; /*case 1:root node is red, then return false*/ if (T->color == 0) return false; /*case 2:compute the number of black nodes in the left subtree*/ /*if the number of black nodes in the right subtree is the same as that in the left subtree,then it proves to be a Red-Black tree otherwise, it is not*/ int count = 0; RBnode *cur = T; while (cur != NULL) { if (cur->color == 1) count++; cur = cur->left; } /*Number records the number of black nodes on each path, and count is used to mark the number of black nodes on the left subtree*/ int number = 0; return _JudgeRBTree(T, count, number); } bool _JudgeRBTree(PRBTree T, int count, int number) { if (T == NULL) return true; /*case 3:continuous red nodes,return false*/ if (((T->color == 0 && (T->left != NULL || T->right != NULL))) && ((T->left->color == 0) || (T->right->color == 0))) { printf("%d ", T->key); printf("There are continuous red nodes!\n"); return false; } if (T->color == 1) number++; /*Leaf node, here we can be used to judge whether the number of black knots is equal*/ if (T->left == NULL && T->right == NULL) { if (number != count) { printf("%d ", T->key); printf("The number of black nodes is different!\n"); return false; } } return _JudgeRBTree(T->left, count, number) && _JudgeRBTree(T->right, count, number); } //测试数据 /*7 -2 1 0 0 5 -4 0 0 0 -11 8 0 0 14 0 -15 0 0*/ /*35 -5 3 0 0 22 -9 0 0 0 47 -40 0 0 0*/ /*11 -2 1 0 0 -7 5 -4 0 0 0 8 0 0 14 0 -15 0 0*/ /*10 -7 5 0 6 0 0 8 0 0 15 -11 0 0 17 0 0*/
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。