[英]Printing the nodes of a tree
我有一個這樣表示的k進制樹:
struct node {
int num;
int data;
struct node **kids;
}
我已經創建了一個函數以打印樹節點的數據。
例:
a
/ | \
b c d
/
e
將打印:
a
b
e
c
d
該函數是:
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]);
}
問題是,我如何還能打印我打印的每個節點的級別。 我試圖聲明一個變量int level = 0; 並增加它,但是它將無法工作,因為遞歸調用將其重置。
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;
}
將另一個參數傳遞給遞歸函數
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);
}
並第一次通過將級別傳遞為零來調用該函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.