Reputation: 922
I have a k-ary tree represented like that:
struct node {
int num;
int data;
struct node **kids;
}
I have created a function in order to print the data of the nodes of the tree.
Example:
a
/ | \
b c d
/
e
will print:
a
b
e
c
d
The function is:
void visit(struct node *head){
int i;
if (head == NULL)
return;
printf("%d\n", head->data);
for (i = 0; i < head->num; i++)
visit(head->kids[i]);
}
Question is, how can I also print the level of each node that i print. I tried to declare a variable int level = 0; and increment it but it won't work because the recursive call resets it.
Upvotes: 0
Views: 634
Reputation: 2688
void visit(struct node *head){ static int i;
if (head == NULL)
return;
printf("%d\n", head->data);
printf("Level : %d\n",i);
for (i = 0; i < head->num; i++)
visit(head->kids[i]);
i = i + 1;
}
Upvotes: 1
Reputation: 4490
Pass another parameter to recursive function
void visit(struct node *head, int level){
int i;
if (head == NULL)
return;
printf("%d : %d\n",level, head->data);
for (i = 0; i < head->num; i++)
visit(head->kids[i], level + 1);
}
And first time, invoke the function by passing level as zero.
Upvotes: 0