有根树的表达(左子右兄弟)

//使用左子右兄弟法表示树节点

#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); //输入id和子节点个数(度)
        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("]\n");

}

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, []
posted @ 2019-03-20 20:24  没尾巴的刺刺鱼  阅读(88)  评论(0编辑  收藏  举报