4.设一棵树T中边的集合为{(A,B),(A,C),(A,D),(B,E),(C,F),(C,G)},要求用孩子兄弟表示法(二叉链表)表示出该树的存储结构并将该树转化成对应的二叉树。
时间: 2024-02-27 18:56:09 浏览: 211
树的孩子兄弟表示法(二叉链表)如下:
```
typedef struct node {
char data;
struct node *first_child; // 指向第一个孩子结点
struct node *next_sibling; // 指向下一个兄弟结点
} node, *tree;
```
根据给定的边集,我们可以画出如下的树形结构:
```
A
/|\
B C D
/ / \
E F G
```
对应的孩子兄弟表示法(二叉链表)如下:
```
typedef struct node {
char data;
struct node *first_child;
struct node *next_sibling;
} node, *tree;
tree create_tree()
{
tree root = (tree)malloc(sizeof(node));
root->data = 'A';
root->first_child = (tree)malloc(sizeof(node));
root->first_child->data = 'B';
root->first_child->first_child = (tree)malloc(sizeof(node));
root->first_child->first_child->data = 'E';
root->first_child->first_child->first_child = NULL;
root->first_child->first_child->next_sibling = NULL;
root->first_child->next_sibling = (tree)malloc(sizeof(node));
root->first_child->next_sibling->data = 'C';
root->first_child->next_sibling->first_child = (tree)malloc(sizeof(node));
root->first_child->next_sibling->first_child->data = 'F';
root->first_child->next_sibling->first_child->first_child = NULL;
root->first_child->next_sibling->first_child->next_sibling = (tree)malloc(sizeof(node));
root->first_child->next_sibling->first_child->next_sibling->data = 'G';
root->first_child->next_sibling->first_child->next_sibling->first_child = NULL;
root->first_child->next_sibling->first_child->next_sibling->next_sibling = NULL;
root->first_child->next_sibling->next_sibling = (tree)malloc(sizeof(node));
root->first_child->next_sibling->next_sibling->data = 'D';
root->first_child->next_sibling->next_sibling->first_child = NULL;
root->first_child->next_sibling->next_sibling->next_sibling = NULL;
return root;
}
```
将该树转换成对应的二叉树,可以按照如下规则进行转换:
1. 将每个结点的第一个孩子作为该结点的左孩子;
2. 将每个结点的其他孩子依次作为该结点右孩子的兄弟。
转换后的二叉树如下:
```
A
/
B
/ \
E C
/ \
F G
\
D
```
阅读全文