Home > Back-end >  For help, the number of leaf nodes in the tree and the tree nodes value for x t in the layer number
For help, the number of leaf nodes in the tree and the tree nodes value for x t in the layer number

Time:09-22

 # include & lt; Stdlib. H> 
#include
# define m 3
# define MAXLEN 20

Typedef char datatype.
Typedef struct node {
Datatype data;
Struct node * child [m].
} the node;
Typedef node * tree;

Tree CreateTree ();/* the preorder traversal sequence set up a 3 c tree, return to the root address */
Int LeafNodes tree (t); The number of leaf nodes in the tree/* o t, the return value for the leaf node number */
Int Level (tree t, datatype x, int h);
/* t o tree nodes value of x in the layer number and h as auxiliary parameters, record the layer tree t,
Return values for the node value for x layer node number, assuming that the root node layer number is 1,
If there are no nodes in the tree t value of node of x, return 0 */

Int main ()
{
Int N, level;
Datatype ch;
The tree t;
T=CreateTree ();
Printf (" \ nthe LeafNodes is: % d \ n ", LeafNodes (t));
The scanf (" % d ", & amp; N); getchar();
While (N -) {
The scanf (" % c ", & amp; Ch); getchar();
Level=level (t, ch, 1);
If (level==0) printf (" the node % c is not exist. \ n ", ch);
The else printf (" the level of the node is % d \ % c n ", ch, level);
}
return 0;
}
Tree CreateTree ()
{
int i;
Char ch;
The tree t;
If ((ch=getchar ())=='#') t=NULL;
The else {
T=(tree) malloc (sizeof (node));
T - & gt; data=https://bbs.csdn.net/topics/ch;
for (i=0; iT - & gt; The child [I]=CreateTree ();
}
return t;
}
Int LeafNodes (tree t)
{
Int n=0;
If (t==NULL) return 0;
Else if (t - & gt; The child [0]==NULL) return 1;
The else
{
for(int i=0; iN +=LeafNodes (t - & gt; The child [I]);
return n;
}
}
Int Level (tree t, datatype x, int h)
{
Int a=0, I;
If (t==NULL) return 0;
The else
{
If (t - & gt; data=https://bbs.csdn.net/topics/=x) return 1;
The else {
H++;
for(i=0; iIf (t - & gt; The child [I]==x) a=1;
A=Level (t - & gt; The child, x, h);
If (a==1) return h;
The else return 0;
}
}
}

Leaders to help me take a look at the second layer of how to write? , the idea of using a recursive;;; !

CodePudding user response:

The second function, without thinking, recursive good difficult,,
  • Related