简体   繁体   中英

Printing the nodes of a tree

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.

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;

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM