用c语言采用孩子兄弟表示法建立一棵树
时间: 2024-03-11 21:48:48 浏览: 23
好的,下面是使用孩子兄弟表示法建立一棵树的c语言代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义树的节点
typedef struct TreeNode{
char data; // 节点数据
struct TreeNode *firstChild; // 第一个孩子节点
struct TreeNode *nextSibling; // 兄弟节点
}TreeNode;
// 创建节点
TreeNode* createNode(char data){
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->firstChild = NULL;
node->nextSibling = NULL;
return node;
}
// 插入孩子节点
void insertChild(TreeNode* parent, TreeNode* child){
if(parent == NULL || child == NULL){
return;
}
if(parent->firstChild == NULL){
parent->firstChild = child;
}else{
TreeNode* sibling = parent->firstChild;
while(sibling->nextSibling != NULL){
sibling = sibling->nextSibling;
}
sibling->nextSibling = child;
}
}
// 先序遍历
void preorderTraversal(TreeNode* node){
if(node == NULL){
return;
}
printf("%c ", node->data);
preorderTraversal(node->firstChild);
preorderTraversal(node->nextSibling);
}
// 测试
int main(){
// 建立一棵树
TreeNode* A = createNode('A');
TreeNode* B = createNode('B');
TreeNode* C = createNode('C');
TreeNode* D = createNode('D');
TreeNode* E = createNode('E');
TreeNode* F = createNode('F');
TreeNode* G = createNode('G');
insertChild(A, B);
insertChild(B, C);
insertChild(B, D);
insertChild(A, E);
insertChild(E, F);
insertChild(F, G);
// 先序遍历
printf("先序遍历结果:");
preorderTraversal(A);
printf("\n");
return 0;
}
```
这里建立了一棵树,以A为根节点,B和E为它的两个孩子节点,B节点下又有C和D两个孩子节点,E节点下又有F孩子节点,F节点下又有G孩子节点。最后使用先序遍历打印出整棵树的节点数据,结果为:A B C D E F G。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)