Code bai tap Cay
Trang 1 trong tổng số 1 trang
Code bai tap Cay
File *.h
- Code:
#include<iostream>
using namespace std;
typedef int TypeInfo;
struct Node
{
TypeInfo data;
Node * left;
Node * right;
};
typedef Node * Nodeptr;
- Code:
#include <iostream>
#include "cay.h"
using namespace std;
void InitBST(Nodeptr &r)// khoi tao nut
{
r=NULL;
}
void PreOrder(Nodeptr &r) // duyet Node - left - right
{
if(r!=NULL)
{
cout<<r->data<<" ";
PreOrder(r->left);
PreOrder(r->right);
}
}
void InOrder(Nodeptr &r)
{
if(r!=NULL)
{
InOrder(r->left);
cout<<r->data<<" ";
InOrder(r->right);
}
}
void Insert(Nodeptr &r, TypeInfo a)
{
if(r==NULL)
{
r= new Node;
r->data=a;
r->left=r->right=NULL;
cout<<"Them thanh cong\n";
}
else
{
if(a<r->data)
return Insert(r->left,a);
else if(a>r->data)
return Insert(r->right,a);
else
cout<<"Them that bai\n";;
}
}
Nodeptr timkiem(Nodeptr r, TypeInfo a)
{
if(r==NULL)
return NULL;
if(a<r->data)
return timkiem(r->left,a);
else if(a>r->data)
return timkiem(r->right,a);
else
return r;
}
int menu()
{
int chon;
cout<<"\t\t\t MENU";
cout<<"\n 1. Chen. ";
cout<<"\n 2. Duyet PreOrder (NLR).";
cout<<"\n 3. Duyet InOrder (LNR).";
cout<<"\n 4. Tim kiem.";
cout<<"\n 5. Nhap -99 de thoat. ";
cout<<"\n Nhap lua chon: ";
cin>>chon;
cin.ignore();
return chon;
}
void main()
{
Nodeptr root;
InitBST(root);
TypeInfo chen;
int ok;
do
{
ok=menu();
switch(ok)
{
case 1:
cout<<"Nhap 1 so can chen: ";
cin>>chen;
cin.ignore();
Insert(root,chen);
break;
case 2:
cout<<"\n Duyet PreOrder: ";
PreOrder(root);
cout<<"\n";
break;
case 3:
cout<<"\n Duyet InOrder";
InOrder(root);
cout<<"\n";
break;
case 4:
int tim;
Nodeptr tk;
cout<<"\nNhap so can tim";
cin>>tim;
cin.ignore();
tk=timkiem(root,tim);
if(tk==NULL)
cout<<"\nKhong tim thay.";
else
cout<<"\n Co so "<<tk->data <<" trong BST";
break;
default:
cout<<"\n Lua chon khong hop le";
break;
}
}
while (ok!=-99);
}
Trang 1 trong tổng số 1 trang
Permissions in this forum:
Bạn không có quyền trả lời bài viết
|
|