#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=https://bbs.csdn.net/topics/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=https://bbs.csdn.net/topics/=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;
}
}
}
大佬們幫我看看第二個求層數的怎么寫呢?,用遞回的思想;;;!
uj5u.com熱心網友回復:
第二個函式,沒有思路,遞回好難啊。。轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64612.html
標籤:C語言
