删除树节点段错误,不会改啊,忘高手指点,谢谢
程序代码:#include<stdio.h>
#include<stdlib.h>
#define N 10
typedef struct tree{
int data;
struct tree *left;
struct tree *right;
}Tree;
void insert_tree(Tree *root,int value)
{
while(root)
{
if(root->data==value) return;
if(root->data>value)
{
if(root->left) root=root->left;
else
{
Tree *t=init_tree(value);
root->left=t;
return;
}
}
else//(root->data<value)
{
if(root->right) root=root->right;
else
{
Tree *t=init_tree(value);
root->right=t;
return;
}
}
}
}
void inorder(Tree *root)
{
if(root==NULL) return;
inorder(root->left);
printf("%d\n",root->data);
inorder(root->right);
}
void levelorder(Tree *root)
{
Tree *t;
Queue *q=(Queue *)malloc(sizeof(Queue));
init_queue(q);
inqueue(q,root);
while(q->f!=q->r)
{
t=dequeue(q);
printf("%d\n",t->data);
if(t->left) inqueue(q,t->left);
if(t->right) inqueue(q,t->right);
}
}
Tree *search_max(Tree *root)//找一个节点可以取代找到的那个节点
{
Tree *temp;
if(!root->right&&!root->left) return NULL;
if(!root->right&&root->left)
{
temp=root->left;
root->left=NULL;
return temp;
}
if(root->right&&!root->left)
{
temp=root->right;
root->right=NULL;
return temp;
}
if(root->right&&root->left&&root->left->right==NULL)
{
temp=root->right;
root->right=NULL;
return temp;
}
root=root->left;
while(root->right->right)
root=root->right;
temp=root->right;
root->right=NULL;
return temp;
}
Tree *search(Tree *root,int value)
{
if(root==NULL) return NULL;
if(root->data==NULL) return NULL;
while(1)
{
if(root->data>value)
{
if(root->left==NULL) return NULL;
else if(root->left->data==value)
return root;
else
root=root->left;
}
if(root->data<value)
{
if(root->right==NULL) return NULL;
else if(root->right->data==value)
return root;
else
root=root->right;
}
}
}
int extent(Tree *root)//计算节点的度
{
if(!root->right&&root->left)
return 0;
if(root->right&&!root->left)
return 1;
if(root->right&&root->left)
return 2;
}
void delet_tree(Tree *root,int value)
{
Tree *s;
Tree *node;
Tree *temp;
if(!search(root,value)) return ;
node=search(root,value);
if(node->left->data==value)
{
temp=search_max(node->left);
if(!temp)
{
s=node->left;
node->left=NULL;
free(s);
}
else
{
s=node->left;
node->left=temp;
if(extent(s)==0)
{
temp->left=s->left;
}
if(extent(s)==1)
{
temp->right=s->right;
}
if(extent(s)==2)
{
temp->left=s->left;
temp->right=s->right;
}
free(s);
}
}
if(node->right->data==value)
{
temp=search_max(node->right);
if(!temp)
{
s=node->right;
node->right=NULL;
free(s);
}
else
{
s=node->right;
node->right=temp;
if(extent(s)==0)
{
temp->right=s->right;
}
if(extent(s)==1)
{
temp->left=s->left;
}
if(extent(s)==2)
{
temp->left=s->left;
temp->right=s->right;
}
free(s);
}
}
}
void main()
{
int i;
Tree *root=(Tree *)malloc(sizeof(Tree));
root->data=N/2;
root->right=NULL;
root->left=NULL;
for(i=0;i<N;i++)
insert_tree(root,random()%N);
//levelorder(root);
delet_tree(root,7);
levelorder(root);
}






