c语言以二叉链表结构存储二叉树,并实现二叉树的生成和遍历
时间: 2024-01-23 07:40:26 浏览: 107
二叉链表结构是指用指针来表示二叉树中每一个节点的左右孩子以及父节点。在C语言中,可以通过定义一个结构体来实现二叉链表结构的存储。具体代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
struct TreeNode *parent;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
node->parent = NULL;
return node;
}
void insertNode(struct TreeNode* parent, struct TreeNode* node, int direction) {
if (direction == 0) {
parent->left = node;
} else {
parent->right = node;
}
node->parent = parent;
}
struct TreeNode* createTree(int* nums, int size) {
if (size == 0) {
return NULL;
}
struct TreeNode* root = createNode(nums[0]);
struct TreeNode* queue[size];
int front = 0;
int rear = 0;
queue[rear++] = root;
int i;
for (i = 1; i < size; i += 2) {
struct TreeNode* parent = queue[front++];
if (nums[i] != -1) {
struct TreeNode* left = createNode(nums[i]);
insertNode(parent, left, 0);
queue[rear++] = left;
}
if (i + 1 < size && nums[i + 1] != -1) {
struct TreeNode* right = createNode(nums[i + 1]);
insertNode(parent, right, 1);
queue[rear++] = right;
}
}
return root;
}
void inorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
void preorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
void postorderTraversal(struct TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
int main() {
int nums[] = {1, 2, 3, 4, 5, 6, -1, -1, -1, 7, 8};
int size = sizeof(nums) / sizeof(int);
struct TreeNode* root = createTree(nums, size);
printf("Inorder traversal: ");
inorderTraversal(root);
printf("\n");
printf("Preorder traversal: ");
preorderTraversal(root);
printf("\n");
printf("Postorder traversal: ");
postorderTraversal(root);
printf("\n");
return 0;
}
```
上述代码中,createNode函数用于创建一个节点,insertNode函数用于在父节点和子节点之间建立关联,createTree函数用于根据给定的数组创建一棵二叉树,inorderTraversal函数、preorderTraversal函数和postorderTraversal函数分别实现了中序遍历、前序遍历和后序遍历。其中,-1表示该节点为空节点。运行上述代码,输出结果如下:
```
Inorder traversal: 4 2 5 1 7 3 8 6
Preorder traversal: 1 2 4 5 3 7 8 6
Postorder traversal: 4 5 2 8 7 3 6 1
```
可以看到,中序遍历、前序遍历和后序遍历分别输出了二叉树的节点值。
阅读全文