//二叉搜索樹的刪除
#include <stdio.h>
#include <stdlib.h>
typedef struct Node
{
int data;
struct Node *leftChild;
struct Node *rightChild;
}Node;
void Build_tree(Node **root);
void Insert_tree(Node **root,Node *new_node);
void Traverse_tree(Node **root);
void Remove_tree(Node **root,int value);//刪除結點
Node** min(Node **root);//右子樹中尋找中序下的第一個結點
void Build_tree(Node **root)//建樹
{
int value;
Node *new_node;
*root=NULL;
new_node=NULL;
printf("請輸入數據,以負數作爲結束\n");
scanf("%d",&value);
while(value>0)
{
new_node=(Node*)malloc(sizeof(Node));
new_node->data=value;
new_node->leftChild=NULL;
new_node->rightChild=NULL;
Insert_tree(root,new_node);
scanf("%d",&value);
}
printf("二叉搜索樹構建完成\n");
}
void Traverse_tree(Node **root)//中序遍歷
{
if(*root!=NULL)
{
Traverse_tree(&((*root)->leftChild));
printf("%d ",(*root)->data);
Traverse_tree(&((*root)->rightChild));
}
}
void Insert_tree(Node **root,Node *new_node)//向樹中插入新節點
{
if(*root==NULL)
*root=new_node;
else if(((*root)->data)>new_node->data)
{
Insert_tree(&((*root)->leftChild),new_node);
}
else if(((*root)->data)<new_node->data)
{
Insert_tree(&((*root)->rightChild),new_node);
}
}
void Remove_tree(Node **root,int x)
{
Node **temp;
if(*root!=NULL)
if(x<((*root)->data)) //要刪除的節點在左子樹中
Remove_tree(&((*root)->leftChild),x);
else if(x>((*root)->data)) //要刪除的節點在右子樹中
Remove_tree(&((*root)->rightChild),x);
else if(((*root)->leftChild)!=NULL&&((*root)->rightChild)!=NULL)//要刪除的就是當前節點
{//當前結點有左子樹和右子樹
printf("*1");
temp=min(&((*root)->rightChild));//獲得右子樹中的最小值
(*root)->data=(*temp)->data;
Remove_tree(&((*root)->rightChild),(*root)->data);
}
else
{//當前節點只有一個子樹或沒有子樹
if((*root)->leftChild!=NULL)//當前節點沒有左子樹
*root=(*root)->leftChild;
else if((*root)->rightChild!=NULL)//當前節點沒有右子樹
*root=(*root)->rightChild;
else
*root=NULL;
}
else
printf("二叉搜索樹是空樹或要刪除的數據不存在!");
}
Node** min(Node** root)
{
// printf("+");
while((*root)->leftChild!=NULL) root=&((*root)->leftChild);
return root;
}
int main(int argc,char *argv[])
{
Node **root;
int value;
Build_tree(root);
printf("\n用插入法建樹的遍歷結果爲:\n");
Traverse_tree(root);
printf("\n請輸入要刪除的數:\n");
scanf("%d",&value);
Remove_tree(root,value);
printf("\n刪除後的遍歷結果爲:\n");
Traverse_tree(root);
system("PAUSE");
return 0;
}
試了好多次應該沒錯。