一、演算法的分析
step1:將a結點按bst樹規則插入紅黑樹中,z是葉子節點;
step2:將z塗紅;
step3:調整使其滿足紅黑樹的性質;
brtnsert演算法
rbinsert(t, z)
p[z] ← y; //y是z的雙親
if y = nil[t] then //z插入空樹
root[t] ← z; //z是根
else
if key[z] < key[y] then
left[y] ← z; //z是y的左子插入
else
right[y] ← z; //z是y的右子插入
left[z] ← right[z] ← nil[t];
color[z] ← red;
rbinsertfixup(t, z);
}rbtnsertfixup調整演算法
rbinsertfixup(t, z)
else //case 2 or case 3 y為黑
else //case 2 or case 3 y為黑
//以下為case 3
color[p[z]]=black; color[p[p[z]]]=red;
rightrotate(t, p[p[z]]); //p[z]為黑,退出迴圈
} //case 1』s endif
} //case 2 or 3』 s
else //case 4,5,6』s 與上面對稱
} //endwhile
color[root[t]] ← black;
}演算法c**:
struct br_node* bt_insert_fixup(struct br_node *t, struct br_node *z)
else
z->parent->color = black;
z->parent->parent->color = red;
t = right_rotate(t,z->parent->parent);}}
else
else
z->parent->color = black;
z->parent->parent->color = red;
t = left_rotate(t,z->parent->parent);
} }}
t->color = black;
return t;
}struct br_node* bt_insert(struct br_node *t, int k)
z->parent = y;
if (y->key == t_nil)
t = z;
else if (z->key key)
y->left = z;
else
y->right =z;
z->left = t->parent;
z->right = t->parent;
z->color = red;
return bt_insert_fixup(t,z);
}二、**
#include #include #include#define t_nil -1
//t_nil is a key of nil[t] in the book.
#define red 1//
#define black 0//the color of node
struct br_node ;
/*output red-black tree in */
int print_node(struct br_node *t)
return 1;
}//left totate
struct br_node * left_rotate(struct br_node *t, struct br_node *x)
//right rotate
struct br_node *right_rotate(struct br_node *t, struct br_node *x)
struct br_node* bt_insert_fixup(struct br_node *t, struct br_node *z)
else
z->parent->color = black;
z->parent->parent->color = red;
t = right_rotate(t,z->parent->parent);}}
else
else
z->parent->color = black;
z->parent->parent->color = red;
t = left_rotate(t,z->parent->parent);
} }}
t->color = black;
return t;
}struct br_node* bt_insert(struct br_node *t, int k)
z->parent = y;
if (y->key == t_nil)
t = z;
else if (z->key key)
y->left = z;
else
y->right =z;
z->left = t->parent;
z->right = t->parent;
z->color = red;
return bt_insert_fixup(t,z);
}int main () ;
t = &brt_nil;
int brt[10] = ;//storage the num which need to insert to red-black tree
printf("需要插入紅黑樹的節點");
srand((unsigned)time(null));
for(int i = 0; i <10; i++)
printf("\n");
for(int i = 0; i < 10; i++)
print_node(t);//output red-black tree
system("pause");
return 1;
}
紅黑樹(插入)
紅黑樹的插入操作相對刪除操作比較簡單。紅黑樹要滿足 任一節點至null的任何路徑,所含黑節點數必須相同。所以,為了滿足此性質,插入節點應該為紅色。如果插入節點的父親為黑色,則不需要進行調整,若為紅色,有三種情況需要討論。1.父節點為紅色,叔節點為紅色 對於這種情況,同時改變父 叔節點顏色為黑色,並將...
紅黑樹插入
一 什麼是紅黑樹 紅黑樹 red black tree 是一種自平衡二叉查詢樹,是在電腦科學中用到的一種資料結構,典型的用途是實現關聯陣列。紅黑樹是一棵二叉搜尋樹,它在每個結點上增加了乙個儲存位來表示結點的顏色,可以是red或black。一棵紅黑樹是滿足下面紅黑性質的二叉搜尋樹 1 每乙個結點或是紅...
紅黑樹 插入
一 滿足下面幾個條件的二叉搜尋樹,稱為紅黑樹 1.任何乙個節點都被著色 紅色或是黑色。2.根節點是黑色的。3.所有的nil節點都看成黑色 nil節點是就是乙個假想的或是無實在意義的節點,所有應該指向null的指標,都看成指向了nil節點。包括葉節點的子節點指標或是根節點的父指標 4.如果乙個節點是紅...