- 主要内容:
使用二叉链表来实现二叉树的存储,编写以下算法:
(1)二叉树的创建
(2)二叉树的前序、中序、后序、层次遍历
(3)完善main()函数的编写,调用以上算法,验证算法的正确性
- 代码模拟实现:
#include<iostream>
using namespace std;
#define null 0
#define maxsize 100
typedef char elemtype;
typedef struct bitNode{
elemtype data;
struct bitNode *lchild;//左孩子指针
struct bitNode *rchild;//右孩子指针
}bitNode,*bitree;
typedef struct
{
bitree elem[maxsize];
int front,rear;//头指针,尾指针
}sequeue;//队列
void EnQueue(sequeue &s,bitree &e)//入队
{
s.elem[s.rear]=e;
s.rear=(s.rear+1)%maxsize;//尾指针移向下一个位置
}
void DeQueue(sequeue &s,bitree &e)//出队
{
e=s.elem[s.front];
s.front=(s.front+1)%maxsize;//头指针移向下一个位置
}
void levelorder(bitree &b)//利用队列性质,层次遍历
{
sequeue s;
s.front=s.rear=0;//初始化队列
bitree t=b;
if(t!=null)
{
EnQueue(s,t);
}
while(s.front!=s.rear){
DeQueue(s,t);
cout<<t->data;
if(t->lchild!=null)//有左子树时,左子树入队
{
EnQueue(s,t->lchild);
}
if(t->rchild!=null)//有右子树时,右子树入队
{
EnQueue(s,t->rchild);
}
}
}
void create(bitree &t)//用递归算法先序创建二叉树
{
char a;
cin>>a;
if(a=='#')//如果a=#,置空 结束递归
{
t=null;
} else{
t=new bitNode;//创建新结点
t->data=a;
create(t->lchild);//递归创建左子树
create(t->rchild);//递归创建右子树
}
}
void preorderTree(bitree &t)//前序遍历,递归算法
{if(t){
cout<<t->data;
preorderTree(t->lchild);//前序遍历左子树
preorderTree(t->rchild);//前序遍历右子树
}
}
void inorderTree(bitree &t)//中序遍历,递归算法
{
if(t)
{
inorderTree(t->lchild);//中序遍历左子树
cout<<t->data;
inorderTree(t->rchild);//中序遍历右子树
}
}
void postorderTree(bitree &t)//后序遍历,递归算法
{
if(t){
postorderTree(t->lchild);//后序遍历左子树
postorderTree(t->rchild);//后序遍历右子树
cout<<t->data;
}
}
int main()
{
bitree t;
create(t);
cout<<"前序遍历为:" ;
preorderTree(t); //前序遍历
cout<<endl;
cout<<"中序遍历为:";
inorderTree(t);//中序遍历
cout<<endl;
cout<<"后序遍历为:";
postorderTree(t);//后序遍历
cout<<endl;
cout<<"层次遍历为:";
levelorder(t);//层次遍历
cout<<endl;
return 0;
}
- 测试运行结果: