目录
前言 :
统一使用如下头文件
创建的3度树
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#define m 3 // 3度树
#define MAXLEN 100
typedef char datatype;
typedef struct node{
datatype data;
struct node*child[m];
}node;
typedef node*tree;
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;
}
//提供测试用例 AB###CE###FH###I####G###D###A
/ | \
B C D
/ | \
E F G
/ \
H I
一、层次遍历
非递归层次遍历函数(队列)
void levelorder(tree t) // 实现树的层次遍历
{
tree queue[100];
int f,r,i;
tree p;
f=0;r=1;queue[0]=t;
while(f<r)
{
p=queue[f];f++;printf("%c",p->data);
for(int i=0;i<m;i++)
{
if(p->child[i])
{
queue[r]=p->child[i];r++;
}
}
}
}
接下来是主函数
int main()
{
tree t;
printf("前按树的前序序列输入结点信息:\n");
t=createtree();
printf("\nthe levelorder is:");
levelorder(t);
return 0;
}
运行结果
二、前序遍历
非递归前序遍历函数 (栈)
void PreOrder1(tree root)
{
tree stack[100];
int top=-1;
while(root||top!=-1)
{
if(root) //根不为空
{
printf("%c",root->data);
for(int i=m-1;i>0;i--) // 前序遍历将孩子结点倒数入栈
{
top++;
stack[top]=root->child[i];
}
root=root->child[0]; // 回到第一个孩子
}
else
root=stack[top--]; // 根为空是取栈顶元素
}
}
接下来是主函数
int main()
{
tree root;
printf("Please input the preorder sequence of the tree:\n");
root=createtree();
printf("前序序列是:\n");
PreOrder1(root);
return 0;
}
运行结果