Tạo cây nhị phân, nhập và xóa! . Ai có cách khác hay hơn thì post lên cho mọi người tham khảo nhá
Mã:
#include <stdio.h>
#include <conio.h>
typedef int TData;
typedef struct Node
{
TData Data;
Node *left;
Node *right;
}Tree;
typedef Node *TTree;
void MakeNullTree(TTree *T)
{
(*T)=NULL;
}
TTree node(TData v,TTree l,TTree r)
{
TTree N;
N=new Node;
N->Data=v;
N->left=l;
N->right=r;
return N;
}
void PreOrder(TTree T)
{
TTree p;
p=T;
if(p!=NULL)
{
printf("%2d",p->Data);
PreOrder(p->left);
PreOrder(p->right);
}
}
void insert(int e, Tree **root)
{
if((*root)==NULL)
{
(*root)=new Tree;
(*root)->Data=e;
(*root)->left=(*root)->right=NULL;
}
else
if(e<(*root)->Data)
insert(e,&(*root)->left);
else
if(e>(*root)->Data)
insert(e,&(*root)->right);
else
printf("Nut nay da ton tai");
}
int xoacucphai(Tree **root)
{
int k;
if((*root)->right==NULL)
{
k=(*root)->Data;
(*root)=(*root)->left;
return k;
}
else
return xoacucphai(&(*root)->right);
}
void xoa(int x,Tree **root)
{
if((*root)!=NULL)
if(x<(*root)->Data)
xoa(x,&(*root)->left);
else if(x>(*root)->Data)
xoa(x,&(*root)->right);
else
if(((*root)->left==NULL)&& ((*root)->right==NULL))
(*root)=NULL;
else
if((*root)->left==NULL)
(*root)=(*root)->right;
else
if((*root)->right==NULL)
(*root)=(*root)->left;
else
(*root)->Data=xoacucphai(&(*root)->left);
}
void main()
{
clrscr();
int i,k,d;
TTree root;
MakeNullTree(&root);
for(i=0;i<10;i++)
{
printf("Nhap gia tri: ");
scanf("%d",&k);
insert(k,&root);
}
printf("Xuat : ");
PreOrder(root);
printf("Nhap ft can xoa : ");
scanf("%d",&d);
xoa(d,&root);
printf("Update : ");
PreOrder(root);
getch();
}