请编写一个C++程序,完成下列算法:
1、 根据扩展二叉树的前序遍历序列,递归构造二叉树;
2、 以广义表的形式输出二叉树;
3、 验证利用栈实现二叉树后序遍历的非递归算法;
4、 利用队列给出二叉树层次遍历的算法。
二叉树以二叉链表方式存储。
#include<iostream.h>
typedef char ElemType;
#define stackSize 30
typedef struct BiNode
{
ElemType data;
BiNode *lchild, *rchild;
}Bino;
void Creat(BiNode *&root)
{
ElemType ch;
cin>>ch;
if(ch=='#')
{root=NULL; }
else {
root=new BiNode;
root->data=ch;
Creat(root->lchild);
Creat(root->rchild);
}
}
void InOrder(BiNode *root) //中序遍历
{
if (root==NULL) return;
else
{
InOrder(root->lchild);
cout<<root->data<<" ";
InOrder(root->rchild);
}
}
void PrinTree(BiNode *root)
{
if(root==NULL) return;
else
{
cout<<root->data;
if(root->lchild != NULL || root->rchild != NULL )
{
cout << "(";
PrinTree(root->lchild);
if(root->rchild != NULL)
cout << ",";
PrinTree(root->rchild);
cout << ")";
}
}
}
void Postorder(BiNode *root)//栈后序非递归遍历
{
BiNode *S[stackSize];
int top=-1;
BiNode *p=root;
BiNode *pre=NULL;
do
{
while (p!=NULL)
{ S[++top]=p;
p=p->lchild;
}
if(top>-1)
{
p=S[top];
if(p->rchild!=NULL && p->rchild!=pre)
p=p->rchild;
else
{
cout<<p->data<<" ";
pre=p;
p=NULL;
top--;
}
}
}while (p!=NULL||top!=-1);
}
void Leveorder(BiNode *root)//队列层序遍历
{
BiNode *Q[30],*p;
int front,rear;
if(root == NULL)
return;
front=0;
rear=0;
Q[++rear]=root;
while(front!=rear)
{
front++;
p=Q[front];
cout<<p->data<<" ";
if(p->lchild!=NULL)
{
rear++;Q[rear]=p->lchild;
}
if(p->rchild!=NULL)
{rear++;Q[rear]=p->rchild;}
}
}
int main()
{
BiNode *root;
cout<<"先序输入,“#”为叶子节点:"<<endl;
Creat(root);
cout<<"中序遍历:";
InOrder(root);
cout<<endl;
cout<<"广义表:";
PrinTree(root);
cout<<endl;
cout<<"栈的后序非递归遍历:";
Postorder(root);
cout<<endl;
cout<<"队列的层序遍历:";
Leveorder(root);
cout<<endl;
return 0;
}