王道数据结构课后代码题p175 06.已知一棵树的层次序列及每个结点的度,编写算法构造此树的孩子-兄弟链表。(c语言代码实现)
/* 此树为
A
B C D
E F G
孩子-兄弟链表为
A
B
E C
F G D
*/
本题代码如下
void createtree(tree* t, char a[], int degree[], int n)
{// 为B数组分配内存tree* B = (tree*)malloc(sizeof(tree) * n);int i = 0;int j = 0;int k = 0;int d = 0;for (i = 0; i < n; i++) {B[i] = (tree)malloc(sizeof(treenode)); // 为每个节点分配内存B[i]->data = a[i];B[i]->lchild = B[i]->rborther = NULL;}for (i = 0; i < n; i++) {d = degree[i];if (d) {k++;B[i]->lchild = B[k];for (j = 2; j <= d; j++) {k++;B[k - 1]->rborther = B[k];}}}*t = B[0]; // 返回根节点
}
完整测试代码为
#include<stdio.h>
#include<stdlib.h>
typedef struct treenode
{char data;struct treenode* lchild, * rborther;
} treenode, * tree;
void createtree(tree* t, char a[], int degree[], int n)
{// 为B数组分配内存tree* B = (tree*)malloc(sizeof(tree) * n);int i = 0;int j = 0;int k = 0;int d = 0;for (i = 0; i < n; i++) {B[i] = (tree)malloc(sizeof(treenode)); // 为每个节点分配内存B[i]->data = a[i];B[i]->lchild = B[i]->rborther = NULL;}for (i = 0; i < n; i++) {d = degree[i];if (d) {k++;B[i]->lchild = B[k];for (j = 2; j <= d; j++) {k++;B[k - 1]->rborther = B[k];}}}*t = B[0]; // 返回根节点
}
void print(tree* t)//先序输出树结点
{if (*t) {printf("%c ", (*t)->data); print(&(*t)->lchild);print(&(*t)->rborther);}
}
int main()
{tree t;char a[7] = "ABCDEFG";int degree[7] = { 3,2,1,0,0,0,0 };createtree(&t, a, degree, 7);print(&t);return 0;
}