CTDL & GT - Tree
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct HD
{
int MHD; // Ma hoa Don
char TCH[30]; // Ten Chu Ho
float ST; // So tien
} HD;
typedef struct node
{
HD data;
struct node *left,*right;
} node;
typedef node *tree;
void nhap (HD *p)
{
char x[5],y[5];
fflush(stdin);
printf("
Nhap Vao Ma Hoa Don: "); gets(x); p->MHD=atoi(x);
fflush(stdin);
printf("
Nhap Vao Ten Chu Ho: "); gets(p->TCH);
fflush(stdin);
printf("
Nhap Vao So Tien: "); gets(y); p->ST=atoi(y);
}
node *taonode(HD p)
{
node *q;
q=(node *)malloc(sizeof(node));
if(q==NULL) { printf("
Day Bo Nho "); exit(1);}
q->data=p;
q->left=NULL;
q->right=NULL;
return q;
}
void tao_cay(tree &root, node *p)
{
if ( root==NULL) root=p;
else {
if(p->data.MHD > root->data.MHD ) tao_cay(root->right,p);
if(p->data.MHD < root->data.MHD ) tao_cay(root->left,p);
}
}
void output(HD p)
{
printf("
MHD: %d\t TenChuHo: %30s \t ST: %.3f",p.MHD,p.TCH,p.ST);
}
void LRN(tree root) // left right node
{
if (root!=NULL)
{
LRN(root->left);
LRN(root->right);
output(root->data);
}
}
void LNR(tree root) // left node right
{
if (root!=NULL)
{
LRN(root->left);
output(root->data);
LRN(root->right);
}
}
void (tree root) // node left right
{
if (root!=NULL)
{
output(root->data);
LRN(root->left);
LRN(root->right);
}
}
node *search(tree &root,int key)
{
node *p;
p=root;
int ok=1;
while(p!=NULL) {
if (p->data.MHD ==key) { return p ; ok=0;}
else if(p->data.MHD < key ) p=p->left;
else p=p->right ;
}
if(ok==1) return NULL;
}
int main(int argc, char *argv[])
{
HD p;
node *q;
int i,n;
root=NULL;
scanf("%d",&n);
for(i=1;i<=n;i++)
{
nhap (&p);
q=taonode(p);
tao_cay(root,q);
}
LRN(root);
node *x;
int key;
printf("
Nhap Vao MHD muon tim: ");scanf("%d",&key);
x= search(root,key);
if (x!=NULL) {
printf("
Hoa Don Muon Tim La: ");
output(x->data);
} else printf("
Khong Tim Thay");
system("pause");
return 0;
}
Bạn đang đọc truyện trên: Truyen247.Pro