#include <iostream.h>
#include <conio.h>
#include <iomanip.h>
struct node{
int item;
struct node *left;
struct node *right;
};
typedef struct node *bistree;
bistree root;
//create a NULL tree
bistree Initbistree (bistree &root)
{
root = NULL;
return (root);
}
// create a new node
bistree create_node(int x)
{
bistree root;
root = new node;
if (root!= NULL)
{ root->left = NULL;
root->right = NULL;
root ->item = x;
}
return (root);
}
//Add new node
bistree Add_Node(bistree &root, int x)
{
bistree NewNode = create_node(x);
if (NewNode == NULL)
return (NewNode);
if (root == NULL)
root = NewNode;
else
{
bistree CurNode = root;
int AddLeft = 1;
while (CurNode->item != x)
{ if (CurNode->item >x)
{ AddLeft = 1;
if (CurNode->left != NULL)
CurNode = CurNode->left;
else
break;
}
else // CurNode->item <x
{ AddLeft = 0;
if (CurNode->right != NULL)
CurNode = CurNode->right;
else
break;
}
}
if (AddLeft == 1)
CurNode->left = NewNode;
else
CurNode->right = NewNode;
}// cua else
return (NewNode);
}
// in ra hinh cay
int haimu(int k){
int kq=1;
if(k==0) kq=1;
else for(int i=1;i<=k;i++) kq*=2;
return kq;
}
void ShowBisTree(bistree root, int x, int y, int k,char direct){
int col;
k--;
col=4+haimu(k);
if (root!=NULL) {
if (direct=='.'){
gotoxy(x,y); cout<<root->item;
}
else if (direct=='\\'){
gotoxy(x,y); cout<<direct;
gotoxy(x,y+1); cout<<root->item;
}
else {
gotoxy(x+5,y); cout<<direct;
gotoxy(x+3,y+1); cout<<root->item;
}
ShowBisTree(root->left, x-col,y+3,k,'/');
ShowBisTree(root->right,x+col,y+3,k,'\\');
}
}
// tim va in ngc cac gtri tu x den goc
void xuatnguoc(bistree & root , int x)
{
if(root==NULL) //root la NULL
cout << "cay NULL";
if(root->item ==x)
cout << "\n gtri la " << root->item;
else if(root->item>x) {
xuatnguoc(root->left,x);
cout << "- " << root->item;
} else {
xuatnguoc(root->right,x);
cout << "- " << root->item;
}
}
//=================
void main(){
clrscr();
int found=0;
int x,i;
bistree root;
Initbistree (root) ;
for (i=0;i<6;i++){
cout << "\n nhap x "; cin >> x;
Add_Node(root,x);
}
// doan ctr in ra cay va tim phan tu x trong cay
//ShowBisTree(root,40,1,5,'.'); cout <<"\n";
//cout<<" \n nhap vao ptu can tim "; cin >>x;
//FindBistree(x, root, found);
//if (found) {
// cout<<"\nCo x trong cay";
// xuatnguoc(root , x); }
//else cout<<"\nKhong co x trong cay";
}
Không có nhận xét nào:
Đăng nhận xét