#include<stdio.h>
#define max 10005
#define NIL -1
struct Node{
int parent, left_child, right_brothor;
};
Node node[max];
int nums;
void init_tree()
{
int id,value;
scanf("%d",&nums);
for(int i = 0; i < max; i++){
node[i].parent = NIL;
node[i].left_child = NIL;
node[i].right_brothor = NIL;
}
int nums_ch,temp;
for(int i = 0; i < nums; i++){
temp = 0;
scanf("%d%d", &id,&nums_ch);
for(int j = 0; j < nums_ch; j++){
scanf("%d", &value);
if(j == 0){
node[id].left_child = value;
}else{
node[temp].right_brothor = value;
}
node[value].parent = id;
temp = value;
}
}
}
void print_child(Node one_node)
{
int c = one_node.left_child;
int flag = 0;
printf("[");
while(c != NIL){
if(flag){
printf(" ");
flag = 0;
}
printf("%d", c);
c = node[c].right_brothor;
flag = 1;
}
printf("]
");
}
int getDepth(Node one_node){
int depth = 0;
int c = one_node.parent;
while(c != NIL){
c = node[c].parent;
depth ++;
}
return depth;
}
int getHeight(Node one_node){
int height = 0;
int c = one_node.left_child;
while(c != NIL){
c = node[c].left_child;
height ++;
}
return height;
}
void print_tree()
{
for(int i = 0; i < nums; i++){
printf("node %d: parent = %d, depth = %d, height = %d, ", i, node[i].parent, getDepth(node[i]), getHeight(node[i]));
if(node[i].parent == NIL){
printf("root, ");
}else if(node[i].left_child == NIL){
printf("leaf, ");
}else{
printf("internal, ");
}
print_child(node[i]);
}
}
int main()
{
init_tree();
print_tree();
return 0;
}
输入
13
0 3 1 4 10
1 2 2 3
2 0
3 0
4 3 5 6 7
5 0
6 0
7 2 8 9
8 0
9 0
10 2 11 12
11 0
12 0
输出
node 0: parent = -1, depth = 0, height = 2, root, [1 4 10]
node 1: parent = 0, depth = 1, height = 1, internal, [2 3]
node 2: parent = 1, depth = 2, height = 0, leaf, []
node 3: parent = 1, depth = 2, height = 0, leaf, []
node 4: parent = 0, depth = 1, height = 1, internal, [5 6 7]
node 5: parent = 4, depth = 2, height = 0, leaf, []
node 6: parent = 4, depth = 2, height = 0, leaf, []
node 7: parent = 4, depth = 2, height = 1, internal, [8 9]
node 8: parent = 7, depth = 3, height = 0, leaf, []
node 9: parent = 7, depth = 3, height = 0, leaf, []
node 10: parent = 0, depth = 1, height = 1, internal, [11 12]
node 11: parent = 10, depth = 2, height = 0, leaf, []
node 12: parent = 10, depth = 2, height = 0, leaf, []