数据结构实验6 树的遍历

#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]的数组,就能实现多重度的树的遍历*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值