树的存储结构代码实现
时间: 2023-11-27 09:50:21 浏览: 52
下面是一个使用邻接表(Adjacency List)存储结构实现树的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义树的节点结构
struct TreeNode {
int value;
struct TreeNode* firstChild;
struct TreeNode* nextSibling;
};
// 创建新节点
struct TreeNode* createNode(int value) {
struct TreeNode* newNode = (struct TreeNode*)malloc(sizeof(struct TreeNode));
newNode->value = value;
newNode->firstChild = NULL;
newNode->nextSibling = NULL;
return newNode;
}
// 添加子节点
void addChild(struct TreeNode* parent, struct TreeNode* child) {
if (parent->firstChild == NULL) {
parent->firstChild = child;
} else {
struct TreeNode* sibling = parent->firstChild;
while (sibling->nextSibling != NULL) {
sibling = sibling->nextSibling;
}
sibling->nextSibling = child;
}
}
// 打印树的结构
void printTree(struct TreeNode* node, int depth) {
if (node == NULL) {
return;
}
for (int i = 0; i < depth; i++) {
printf(" ");
}
printf("%d\n", node->value);
printTree(node->firstChild, depth + 1);
printTree(node->nextSibling, depth);
}
int main() {
// 创建根节点
struct TreeNode* root = createNode(1);
// 创建子节点
struct TreeNode* child1 = createNode(2);
struct TreeNode* child2 = createNode(3);
struct TreeNode* child3 = createNode(4);
// 添加子节点到根节点
addChild(root, child1);
addChild(root, child2);
addChild(root, child3);
// 创建子节点的子节点
struct TreeNode* grandchild1 = createNode(5);
struct TreeNode* grandchild2 = createNode(6);
// 添加子节点的子节点
addChild(child1, grandchild1);
addChild(child2, grandchild2);
// 打印树的结构
printTree(root, 0);
return 0;
}
```
在这个示例中,我们定义了一个`TreeNode`结构体,包含了节点的值、指向第一个子节点的指针`firstChild`和指向下一个兄弟节点的指针`nextSibling`。通过`createNode`函数创建新节点,并使用`addChild`函数将子节点添加到父节点。最后,使用`printTree`函数打印树的结构。
这个示例中创建了一个简单的树,并打印了它的结构:
```
1
2
5
3
6
4
```
你可以根据需要修改和扩展这个示例,以适应不同的树结构。