#include<iostream.h>
#include<malloc.h>
#define maxnode 1000
typedef char elemtype;
typedef struct bintnode
{
elemtype data;
struct bintnode *lchild,*rchild,*parent;
}bintnode,*bintree;
void createbintree(bintree *t) //构建一个二叉树链表
{
char ch;
cin>>ch;
if(ch=='0') *t='/0';
else
{
*t=(bintnode*)malloc(sizeof(bintnode));
(*t)->data=ch;
createbintree(&(*t)->lchild);
createbintree(&(*t)->rchild);
}
}
void preorderout(bintree t) //先序序列的输出
{
if(t)
{
cout<<t->data;
preorderout(t->lchild);
preorderout(t->rchild);
}
}
void inorderout(bintree t) //中序序列的输出
{
if(t)
{
inorderout(t->lchild);
cout<<t->data;
inorderout(t->rchild);
}
}
void postorderout(bintree t) //后序序列的输出
{
if(t)
{
postorderout(t->lchild);
postorderout(t->rchild);
cout<<t->data;
}
}
void leveorder(bintree t) //层次遍历的输出
{
bintree queue[maxnode];
int front,rear;
if(t=='/0') return;
front=-1;
rear=0;
queue[rear]=t;
while(front!=rear)
{
front++;
cout<<queue[front]->data;
if(queue[front]->lchild!='/0')
{
rear++;
queue[rear]=queue[front]->lchild;
}
if(queue[front]->rchild !='/0')
{
rear++;
queue[rear]=queue[front]->rchild ;
}
}
}
//主函数
void main()
{
bintree bt;
cout<<"输入二叉树:";
createbintree(&bt);
cout<<"输出先序遍历:";
preorderout(bt);
cout<<endl;
cout<<"输出中序遍历:";
inorderout(bt);
cout<<endl;
cout<<"输出后序遍历:";
postorderout(bt);
cout<<endl;
cout<<"层次遍历:";
leveorder(bt);
cout<<endl;
}
二叉树问题
最新推荐文章于 2021-05-17 15:14:26 发布