红黑树
红黑树的性质:
1.树中节点要么黑要么红;
2.树中父子节点不能同为红色;
3.终端节点NULL为哨兵节点默认黑色;
4.根节点默认为黑色;
5.任意节点到其所能到达的各个终端节点的路径中的黑节点个数必须完全相同;
红黑树的创建:
红黑树插入由于第五条性质(本文中),所以最好不要插入黑节点(除了你插入根);
所以我们一般创建节点时候先赋值为红,如果是根在变黑;
插入共分为7种情况:
1.插入节点如果为根节点,节点变黑,插入结束;
2.插入节点的父节点如果为黑节点,直接插入,结束;
3.插入节点的父节点为红节点(因为父亲节点为红所以爷爷必定为黑):
3.1 叔叔为红,将叔叔变黑爷爷变红,把爷爷当作新的节点向上调整;
3.2 叔叔为黑:
3.2.1 如果父亲是爷爷的左:
3.2.1.1节点是父亲的右:
将父亲当作插入节点,
以插入节点为支点左旋;
3.2.1.2节点为父亲的左:
父亲变黑,爷爷变红
以爷爷为支点右旋;
结束;
3.2.2如果父亲是爷爷的右:
3.2.2.1节点为父亲的左:
将父亲节点作为插入节点;
以插入节点为支点左旋
3.2.2.2节点为父亲节点的右:
父亲变黑,爷爷变红;
以爷爷为支点右旋;
结束;
BirnaryTree *CreateRBTree(int *arr,int size) { int i = 0; BirnaryTree* pHead = NULL; BirnaryTree*temp = NULL; BirnaryTree *BJ = NULL; while(i<size) //每次循环添加 { temp = (BirnaryTree*)malloc(sizeof(BirnaryTree));//插入基本上红色 temp->nValue = arr[i]; temp->pLeft = NULL; temp->pRight = NULL; temp->color = RED; temp->pFarther = NULL; if(pHead == NULL) //如果是根变黑 { temp->color = BLACK; temp->pFarther = NULL; pHead = temp; }else { BJ = FindInSertPos(pHead,arr[i]);//查找插入的父亲位置 temp->pFarther = BJ; temp->pRight = NULL; temp->pLeft = NULL; if(arr[i]<temp->pFarther->nValue) { temp->pFarther->pLeft = temp; }else { temp->pFarther->pRight = temp; } if(temp->pFarther->color == BLACK)//如果父亲为黑色插入成功继续 { i++; continue; }else //如果父亲为红,看叔叔颜色,爷爷必定为黑 { BirnaryTree *Uncle; BirnaryTree *GrandFather; while(temp->pFarther->color == RED)//父亲为黑调整成功 { if(temp->pFarther->pFarther->pLeft == temp->pFarther) { Uncle = temp->pFarther->pFarther->pRight; }else { Uncle = temp->pFarther->pFarther->pLeft; } GrandFather = temp->pFarther->pFarther; if(Uncle!=NULL&&Uncle->color == RED)//叔叔为红 { temp->pFarther->color = BLACK; Uncle->color = BLACK; GrandFather->color = RED; temp = GrandFather; if(temp == pHead) { temp->color = BLACK; break; } continue; } if(Uncle==NULL||Uncle->color == BLACK)//叔叔为黑 { if(temp->pFarther == GrandFather->pLeft) { if(temp->pFarther->pRight == temp) { temp = temp->pFarther; LeftRotate(&temp,&pHead); }else { temp->pFarther->color = BLACK; GrandFather->color = RED; RightRotate(&GrandFather,&pHead); } }else { if(temp->pFarther->pLeft == temp) { temp = temp->pFarther; RightRotate(&temp,&pHead); }else { temp->pFarther->color = BLACK; GrandFather->color = RED; LeftRotate(&GrandFather,&pHead); } } } } } } i++; } return pHead; }