/* 此树为
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;
}