#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <queue>
#define m 3
#define MAXLEN 100
typedef char datatype;
typedef struct node {
datatype data;
struct node *child[m];
} node;
typedef node *tree;
std::queue<node*> q;
/********************************************************/
/* 函数功能:根据树的前序遍历结果建立一棵3度树 */
/* 函数返回值:树根地址 */
/* 文件名:tree.h,函数名:createtree () */
/********************************************************/
tree createtree()
{/*按前序遍历顺序建立一棵3度树的递归算法*/
int i; char ch;
tree t;
if ((ch=getchar())=='#') t=NULL;
else
{
t=(tree) malloc (sizeof(node));
t->data=ch;
for (i=0;i<m;++i)
t->child[i]= createtree();
}
return t;
}
void preorder(tree t)
{
int i;
if (t)
{
printf("%c",t->data);
for (i=0;i<m;i++)
preorder(t->child[i]);
}
}
void postorder(tree t)
{
int i;
if (t)
{
for (i=0;i<m;i++)
postorder(t->child[i]);
printf("%c",t->data);
}
}
//层序遍历代码
void levelOrder(tree t)
{
while(!q.empty()) q.pop();
q.push(t);
while(1)
{
t = q.front();
if(t)
{
printf("%c",t->data);
q.pop();
if(t->child[0])
q.push(t->child[0]);
if(t->child[1])
q.push(t->child[1]);
if(t->child[2])
q.push(t->child[2]);
}
else break;
}
}
int main()
{ tree t;
t=createtree();
printf("二叉树的前序序列为:\n");
preorder(t);
printf("\n");
printf("\n二叉树的后序序列为:\n");
postorder(t);
printf("\n");
printf("\n二叉树的层序序列为:\n");
levelOrder(t); /*层序非递归遍历二叉树*/
printf("\n");
return 0;
}
/*在遍历二叉树的基础上,只需要把左孩子、右孩子改为child[maxn]的数组,就能实现多重度的树的遍历*/