Napisalem sobie dzis drzewo czerwono czarne, jednak przy dodawaniu nowego elementu rzuca segmentation fault, wiekszosc kodu jest ok, bo wczoraj pisalem zwykle drzewo bst i dzialalo ok.
#include <stdio.h>
#include <stdlib.h> //dla exit
#define RED 0
#define BLACK 1
typedef struct t_node
{
int key;
struct t_node *left;
struct t_node *right;
struct t_node *p;
int kolor;
} node;
node *TN=NULL;
void l_rotate(node **head, node** x);
void r_rotate(node** head, node** x);
void rb_insert(node **head, int k);
void rb_insert_fixup(node** head, node** z);
void node_out(int level, node *nd);
void inorder_tree_walk(int level, node *head);
//void tree_insert(node **head, int k);
node* tree_search(node *temp, int k);
node* iterative_tree_search(node *head, int k);
node* tree_minimum(node* head);
node* tree_maximum(node *head);
node* tree_succesor(node *h);
//node* tree_delete(node *h, int k);
void menu();
node *head=NULL;
node *h=NULL;
.
.
.
void rb_insert(node **head, int k)
{
node *z=(node *)malloc(sizeof(node));
z->key=k;
z->left=NULL;
z->right=NULL;
node* y=NULL;
node* x=(*head);
while (x!=NULL)
{
y=x;
if (z->key < x->key)
x=x->left;
else
x=x->right;
}
z->p=y;
if (y==NULL)
*(head)=z;
else if (z->key < y->key)
y->left=z;
else
y->right=z;
z->left = TN;
z->right = TN;
z->kolor = RED;
rb_insert_fixup(head, &z);
}
////////////////////////////////////////////////////////////////////////////////////////
void l_rotate(node** head, node** x) //x i head moga byc tu modyfikowane wiec koniecznie trzeba wskaznik na wskaznik, prawda? ;)
{
node *y = (*x)->right;
(*x)->right=y->left;
y->left->p =(*x);
y->p =(*x)->p;
if ((*x)->p == TN)
(*head)=y;
else if ((*x) == (*x)->p->left)
(*x)->p->left = y;
else
(*x)->p->right = y;
y->left = (*x);
(*x)->p = y;
}
///////////////////////////////////////////////////////////////////////////////
void r_rotate(node** head, node** x)
{
node *y = (*x)->left;
(*x)->left=y->right;
y->right->p =(*x);
y->p =(*x)->p;
if ((*x)->p == TN)
(*head)=y;
else if ((*x) == (*x)->p->right)
(*x)->p->right = y;
else
(*x)->p->left = y;
y->right = (*x);
(*x)->p = y;
}
/////////////////////////////////////////////////////////////////////////////////////
void rb_insert_fixup(node** head, node** z) //podobnie koniecznie ** ?
{
node *y=NULL;
while ((*z)->p->kolor == RED)
{
if ((*z)->p==(*z)->p->p->left)
{
y=(*z)->p->p->right;
if (y->kolor == RED)
{
(*z)->p->kolor = BLACK;
y->kolor = BLACK;
(*z)->p->p->kolor = RED;
*z = (*z)->p->p;
}
else if (*z==(*z)->p->right)
{
*z = (*z)->p;
l_rotate(head, z);
(*z)->p->kolor = BLACK;
(*z)->p->p->kolor = RED;
r_rotate(head, &(*z)->p->p);
}
else
{
*z = (*z)->p;
r_rotate(head, z);
(*z)->p->kolor = BLACK;
(*z)->p->p->kolor = RED;
l_rotate(head, &(*z)->p->p);
}
}
}
(*head)->kolor=BLACK;
}