PDA

View Full Version : Xin text giùm thuật toán duyệt cây tổng quát



ahappyboy89
24-05-2009, 23:10
Các bạn giúp mình text bài này chút.Chuong trình chạy rồi nhưng hình như thuật toán vẫn chưa đúng lắm ...Khi thêm 1 nhánh mới từ nhánh con lại ko được


#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <alloc.h>
#include<assert.h>
#define TRUE 1
#define FALSE 0
#define max 10
struct nodetype
{
int info;
int snut;
struct nodetype *data[max];
};
typedef struct nodetype *Tree;
Tree T,p;
int found;
int empty(Tree T)
{
return(T == NULL ? TRUE : FALSE);
}
void taonutgoc(){
int a,b,c;
if(!empty(T)) printf("cay da co nut goc");
else{
printf("nhap gia tri nut goc");scanf("%d",&a);
T=(Tree) malloc(sizeof(struct nodetype));
p =( Tree) calloc(1, sizeof(struct nodetype) );
T->info=a;
T->snut=0;
for(int i=0;i<max;i++)
T->data[i]=NULL;
}
};
Tree search(Tree T1,int k){
int i;
found=0;
if(T1){
if(T1->info==k) { found=1;
return (T1);
}
i=T1->snut;
for(i=0;i<T1->snut;i++){
search(T1->data[i],k);
}
}
}
void themnut(){
int a,c,d,e;
Tree s,T2,b;
T2=T;
b=(Tree) malloc(sizeof(struct nodetype));
printf("nhap 1 gia tri nut can them:");scanf("%d",&a);
b=search(T2,a);
if(found) printf("Khoa bi trung,ko them dc");
else{
printf("nhap khoa cua nut cha");scanf("%d",&c);
// T2=T;
b=search(T2,c);
if(found==0) printf("khong tim thay nut cha");
else {
s=(Tree) malloc(sizeof(struct nodetype));
s->info=a;
s->snut=0;
for(int i=0;i<=s->snut;i++) s->data[i]=NULL;
b->snut++;
b->data[b->snut-1]=s;
}
}
}
void duyetcay(Tree T1){
int i;
if(T1==NULL) return;
else
printf("%d",T1->info);
for(i=0;i<T1->snut;i++){
duyetcay(T1->data[i]);
}
}
void xoacay(Tree T1){
int i;
for(i=0;i<T1->snut;i++){
xoacay(T1->data[i]);
free(T1);
} }

void main(){
int chucnang;
do
{
// menu chinh cua chuong trinh
printf("\n\nCAY TONG QUAT)");
printf("\n\nCac chuc nang cua chuong trinh:\n");
printf(" 1: Them nut goc\n");
printf(" 2: Them nut con\n");
printf(" 3: Duyet cay \n");
printf(" 4: xoa toan bo cay \n");
printf(" 0: Ket thuc chuong trinh\n");
printf("Chuc nang ban chon: ");
scanf("%d", &chucnang);
switch(chucnang)
{
case 1: { taonutgoc();
break;}
case 2: {
themnut();
break;
}
case 3 :{
duyetcay(T);
break;
}
case 4:{
xoacay(T);break;
}
}
} while(chucnang!=0) ;
}