//二叉树的建立‘先序遍历’中序‘后序遍历
#include<iostream.h>
#include<stdlib.h>
typedef char ElemType;
typedef struct BinaryTree{
ElemType data;
struct BinaryTree *lchild, *rchild;
};
void CreatBiTree (BinaryTree *BT) //按先序遍历二叉树
{
cout<<"\nInput datas to creat binarytree, use ^ to ned, use Enter to device two datas!"<<endl;
char ch;
cin>>ch;
if(ch=='^') BT=NULL;
else{
BT=(BinaryTree*)malloc(sizoef(BinaryTree));
if(!BT) Error("Fail to malloc space!");
BT->data=ch;
CreatBiTree(BT->lchild);
CreatBiTree(BT->rchild);
}
}
//二叉树的遍历
void TraverBiTree(BinaryTree *BT,int mark)
{
switch(mark)
{
case 1: //先序遍历
if(BT!=NULL)
{cout<<BT->data<<" ";
TraverBiTree(BT->lchild,mark);
TraverBiTree(BT->rchild,mark);
}//if
case 2: //中序遍历
if(BT!=NULL){
TraverBiTree(BT->lchild,mark);
cout<<BT->data<<" ";
TraverBiTree(BT->rchild,mark);
}//if
case 3: //后序遍历
if(BT!=NULL){
TraverBiTree(BT->lchild,mark);
TraverBiTree(BT->rchild,mark);
cout<<BT->data<<" ";
}//if
case 4: //按层次遍历
const MaxLength=30;
BinaryTree *Q[MaxLength]; //定义存储二叉树结点指针的数组空间作为队列用
int front=0,rear=0,
BinaryTree *p;
if(BT!=NULL){
rear=(rear+1)%MaxLength ; //队尾指针后移
Q[rear]=BT;
}//if
while(front!=rear)
{
front=(front+1)%Maxlength;
p=Q[front];
cout<<p->data<<" ";
if(p->lchild!=NULL)
{ rear=rear+1)%MaxLength;
Q[rear]=p->lchild;
}//if
if(p->rchild!=NULL)
{
rear=(rear+1)%MaxLength;
Q[rear]=p->rchild;
}//if
}
default:
cerr<<"\nmark is out of range! fail to traverBiTree!"<<endl;
getch();
exit(1);
}
}
void Error(char *ms)
{
cout<<*ms<<endl;
exit(1);
}
void main()
{
BinaryTree *BT;
//int mark,i,j;
//ElemType elem;
int flag1, flag2;
cout<<"\nThis is a BinaryTree : 1: Creat Binary Tree 2:Traver binary tree
cin>>flag1;
switch(flag1)
{
case 1:
CreatBiTree(BT);
break;
case 2:
int flag;
cout<<"\n1:preorder creat 2: In Order Treaver 3: Post Order Traver
4: levels Order Traver"<<endl;
cin>>flag;
if(flag==1)
TraverBiTree(BT,1); //先序遍历
else if(flag==2)
TraverBiTree(BT,2); //中序遍历
else if(flag==3)
TraverBiTree(BT,3); //后序遍历
else if(flag==4)
TraverBiTree(BT,4); //按层次遍历
else
cout<<"\nYou must select 1-4"<<endl;
break;
defualt:
cout<<"\nYou must select 1-2"<<endl;
break;
}
}
Word教程网 | Excel教程网 | Dreamweaver教程网 | Fireworks教程网 | PPT教程网 | FLASH教程网 | PS教程网 |
HTML教程网 | DIV CSS教程网 | FLASH AS教程网 | ACCESS教程网 | SQL SERVER教程网 | C语言教程网 | JAVASCRIPT教程网 |
ASP教程网 | ASP.NET教程网 | CorelDraw教程网 |