struct search_tree
{
struct search_tree *lchild;
struct search_tree *rchild;
struct search_tree *parent;
void *private_data;
};
struct search_tree *make_empty(struct search_tree *T)
{
if( T != NULL)
{
make_empty(T->lchild);
make_empty(T->rchild);
free(T);
}
return NULL;
}
struct search_tree *find_node(element x, const struct search_tree *T)
{
const struct search_tree *tmp = T;
if ( tmp != NULL)
{
if( tmp->private_data != x)
{
if( x>tmp->private_data )
tmp = tmp->rchild;
else
tmp = tmp->lchild;
return find(x,tmp);
}
else if(tmp->private_data == x)
return tmp;
else
return NULL;
}
return NULL;
}
//递归实现
struct search_tree *find_min(const struct search_tree *T)
{
struct search_tree *tmp = T;
if(tmp!=NULL)
if(tmp->lchild != NULL)
return find_min(tmp->lchild);
return tmp;
}
//循环实现
struct search_tree *find_min(const struct search_tree *T)
{
struct search_tree *tmp;
tmp = T;
if( T!=NULL)
while(tmp->lchild != NULL)
tmp = tmp->lchild;
return tmp;
}
//递归实现
struct search_tree *find_max(cosnt struct search_tree *T)
{
struct search_tree *tmp;
tmp = T;
if(tmp != NULL)
if(tmp->lchild != NULL)
return find_max(tmp->lchild);
return tmp;
}
//循环实现
struct search_tree *find_max(const struct search_tree *T)
{
struct search_tree *tmp;
tmp = T;
if(T != NULL)
while(tmp->rchild != NULL)
tmp = tmp->rchild;
return tmp;
}
struct search_tree *insert( element x , const struct search_tree T)
{
struct search_tree *tmp = T;
struct search_tree *new_node = (struct search_tree *)malloc(sizeof(struct search_tree));
new_node -> private_data = x;
if( T!=NULL && x!=T->private_data )
{
if(new_node->private_data > T->private_data)
tmp = T-> rchild;
else
tmp = T->lchild;
insert(x,tmp);
}
else
tmp = new_node;
return tmp;
}
int delete( element x, const struct search_tree T)
{
struct search_tree *tmp, *del_node, *rpl_node;
tmp = T;
if( T != NULL)
{
if( (del_node = find_node(element x, const struct search_tree T)) !=NULL )
{
if(del_node->rchild != NULL)
{
rpl_node = find_min(del_node->rchild);
rpl_node->parent = del_node->parent;
rpl_node->lchild = del_node->lchild;
if(del_node->rchild != rpl_node)
del_node->rchild->parent = rpl_node;
else
rpl_node->parent->lchild = NULL;
}
else
{
del_node->lchild->parent = del_node->parent;
del_node->lchild = del_node->lchild;
}
free(del_node);
del_node = NULL;
return 1;
}
else
return 0;
}
return 0;
}
阅读(1486) | 评论(0) | 转发(0) |