C語言動態構造紅黑樹
貼出核心程式碼和效果圖。希望共同學習交流進步。
void leftRotate(Tnode* root,Tnode x){ Tnode y = x->r; x->r = y->l; //y->l = x; if(y->l!=tnil) (y->l)->p = x; y->p = x->p; if(x==*root){ *root = y; }else{ if(x==(x->p)->l){ (x->p)->l = y; }else if(x==(x->p)->r){ (x->p)->r = y; } } y->l = x; x->p = y; } void rightRotate(Tnode* root,Tnode y){ Tnode x = y->l; y->l = x->r; if(x->r!=tnil){ (x->r)->p = y; } x->p = y->p; if(y==*root){ *root = x; }else{ if(y==(y->p)->r){ (y->p)->r = x; }else{ (y->p)->l = x; } } x->r = y; y->p = x; } void fixUp(Tnode* root,Tnode z){ while((z->p)->color==1){ if(z->p==((z->p)->p)->l){ //情況1:叔節點為紅色 Tnode y = ((z->p)->p)->r; if(y->color==1){ (z->p)->color = 0; y->color = 0; z = ((z->p)->p); z->color = 1; }else{ //2 if(z==(z->p)->r){ z = z->p; //進行左旋。轉化為情況3 leftRotate(root,z); } //3 (z->p)->color = 0; ((z->p)->p)->color = 1; rightRotate(root,(z->p)->p); } }else{ //對稱處理 Tnode y = ((z->p)->p)->l; //情況4 if(y->color==1){ (z->p)->color = 0; y->color = 0; z = ((z->p)->p); z->color = 1; }else{ //5 if(z==(z->p)->l){ z = z->p; rightRotate(root,z); } (z->p)->color = 0; ((z->p)->p)->color = 1; leftRotate(root,(z->p)->p); } } } (*root)->color = 0; } void insertTnode(Tnode* root,int key){ Tnode z = (Tnode)malloc(sizeof(struct tnode)); Tnode temp = *root; Tnode temp1 = temp; if(*root==NULL){ *root = z; temp1 = tnil; }else{ while(temp!=tnil){ if(key>temp->key){ temp1 = temp; temp = temp->r; }else{ temp1 = temp; temp = temp->l; } } if(key>temp1->key){ temp1->r = z; }else{ temp1->l = z; } } z->p = temp1; z->r = tnil; z->l = tnil; z->key = key; z->color = 1;//設定為紅色。以保證不會違反性質5 fixUp(root,z); }
效果圖