#include"tree.h"voidlevelorder(tree t)/* t为指向树根结点的指针*/{
tree queue[MAXLEN];/*用队列存放待处理的结点*/int head=0,end=1;int i;
queue[head]= t;/*先将根节点入队*/while( head < end ){for(i=0;i<m;i++)/*将队列中结点的下一层结点入队,逐层入队*/{if( queue[head]->child[i]){
queue[end++]= queue[head]->child[i];}}printf("%c",queue[head++]->data);/*逐层出队*/}}intmain(){
tree t;printf("please input the preorder sequence of the tree:\n");
t=createtree();printf("\nthe levelorder is:");levelorder(t);return0;}
#include"tree.h"voidPreOrder1(tree root){
tree stack[100];int i;int top=-1;while(root || top!=-1){if(root){printf("%c",root->data);//输出根结点for(i=m-1;i>0;i--)//所有非空孩子结点进栈if(root->child[i]!=NULL){
top++;
stack[top]=root->child[i];}
root=root->child[0];//转第1棵子树}else{
root=stack[top--];//栈顶树出栈}}}int main (){
tree root;printf("please input the preorder sequence of the tree:\n");
root =createtree();printf("前序序列是:\n");PreOrder1(root);return0;}
#include"tree.h"intPostOrder1(tree root){
tree treeStack[MAXLEN];/*储存待处理的结点*/int top =-1;
tree printStack[MAXLEN];/*储存已经处理完子树的、待输出的结点*/int topp =-1;int i;if( root ) treeStack[++top]= root;/*根结点进栈*/while( top !=-1){
root = treeStack[top--];/*取一个待处理结点root*/for(i=0;i<m;i++)/*将root的所有子结点进栈*/{if( root->child[i]) treeStack[++top]= root->child[i];}
printStack[++topp]= root;/*处理完root、将root进printStack*/}while( topp !=-1)printf("%c",printStack[topp--]->data);/*输出后序序列*/}intPostOrder2(tree root){
tree treeStack[MAXLEN];/*未处理完的结点*/int subStack[MAXLEN];/*正在处理的孩子的下标*/int top =-1;
tree p;int i;
treeStack[++top]= root;
subStack[top]=0;/*首先处理child[0]这个分支*/while( top !=-1){
p = treeStack[top];while( subStack[top]< m )/*处理所有分支*/{
i = subStack[top];if( p->child[i]){
p = p->child[i];
treeStack[++top]= p;/*有孩子则入栈*/
subStack[top]=0;/*并处理刚入栈结点的child[0]*/}else{
subStack[top]++;/*该分支没有孩子,处理下一分支*/}}printf("%c",p->data);/*出栈前再输出*/
top--;/*该结点处理完毕,返回处理父结点的child[i+1]*/
subStack[top]++;}}int main (){//AB###CE###FH###I####G###D### ,测试三度树
tree root;printf("please input the preorder sequence of the tree:\n");
root =createtree();printf("后序序列是:\n");PostOrder1(root);putchar('\n');PostOrder2(root);return0;}
4、假设树采用指针方式的孩子表示法表示,试编写一个函数int equal(tree t1, tree t2),判断两棵给定的树是否等价(两棵树等价当且仅当其根结点的值相等且其对应的子树均相互等价)。
#include"tree.h"#define TRUE 1#define FALSE 0intequal(tree t1,tree t2){int flag=TRUE,i;if(t1==NULL&& t2==NULL)return TRUE;elseif(t1==NULL&& t2!=NULL|| t2==NULL&& t1!=NULL)return FALSE;elseif(t1->data!=t2->data)return FALSE;else{for(i=0;i<m;i++)
flag=flag&&equal(t1->child[i],t2->child[i]);return flag;}}int main (){
tree t1,t2;printf("please input the preorder sequence of the tree:\n");
t1=createtree();getchar();printf("please input the preorder sequence of the tree:\n");
t2=createtree();if(equal(t1,t2)== TRUE){
printf ("两树相等\n");}else{
printf ("两树不相等\n");}return0;}