69,371
社区成员
发帖
与我相关
我的任务
分享
#include <stdlib.h>
#include <malloc.h>
#define m 3
#define MAXLEN 20
typedef char datatype;
typedef struct node {
datatype data;
struct node *child[m];
} node;
typedef node *tree;
tree CreateTree(); /*按前序遍历顺序建立一棵3度树,返回树根地址 */
int LeafNodes(tree t); /* 求树t中叶子结点的个数,返回值为叶子结点个数*/
int Level(tree t,datatype x,int h);
/* 求树t中结点值为x的结点的层号,h为辅助参数,记录树t的层号,
返回值为结点值为x的结点层号,假设根结点的层号为1。
若树t中不存在结点值为x的结点,返回0*/
int main()
{
int N,level;
datatype ch;
tree t;
t=CreateTree();
printf("\nthe LeafNodes is:%d\n",LeafNodes(t));
scanf("%d",&N);getchar();
while(N--){
scanf("%c",&ch);getchar();
level=Level(t,ch,1);
if (level==0) printf("the node %c is not exist.\n",ch);
else printf("the level of the node %c is %d\n",ch,level);
}
return 0;
}
tree CreateTree()
{
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;
}
int LeafNodes(tree t)
{
int n=0;
if(t==NULL) return 0;
else if(t->child[0]==NULL) return 1;
else
{
for(int i=0;i<m;i++)
n+=LeafNodes(t->child[i]);
return n;
}
}
int Level(tree t,datatype x,int h)
{
int a=0,i;
if(t==NULL) return 0;
else
{
if(t->data==x) return 1;
else{
h++;
for(i=0;i<m;i++)
if(t->child[i]==x) a=1;
a=Level(t->child,x,h);
if(a==1) return h;
else return 0;
}
}
}
int Level(tree t,datatype x,int h)
{
if(t)
{
if(t->data==x) return h;
else
return Level(t->child[0],x,h+1)+Level(t->child[1],x,h+1)+Level(t->child[2],x,h+1);
}
else return 0;
}
非本人所写,搬运工罢了。
原作者:https://blog.csdn.net/qq_51602939/article/details/116197124