帮我用c语言写一个完整的二叉树功能代码,包括前序中序后序层序的构造创建变量销毁方法
时间: 2024-05-09 11:14:18 浏览: 93
好的,以下是一个完整的二叉树功能代码,包括前序、中序、后序、层序的构造、创建、变量销毁方法。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 构造二叉树
TreeNode* buildTree(int* preorder, int* inorder, int preStart, int preEnd, int inStart, int inEnd) {
if (preStart > preEnd || inStart > inEnd) {
return NULL;
}
TreeNode* root = (TreeNode*)malloc(sizeof(TreeNode));
root->data = preorder[preStart];
int inorderRootIndex = inStart;
for (int i = inStart; i <= inEnd; i++) {
if (inorder[i] == preorder[preStart]) {
inorderRootIndex = i;
break;
}
}
int leftSubTreeSize = inorderRootIndex - inStart;
root->left = buildTree(preorder, inorder, preStart + 1, preStart + leftSubTreeSize, inStart, inorderRootIndex - 1);
root->right = buildTree(preorder, inorder, preStart + leftSubTreeSize + 1, preEnd, inorderRootIndex + 1, inEnd);
return root;
}
// 前序遍历
void preorderTraversal(TreeNode* root) {
if (root != NULL) {
printf("%d ", root->data);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
}
// 中序遍历
void inorderTraversal(TreeNode* root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}
// 后序遍历
void postorderTraversal(TreeNode* root) {
if (root != NULL) {
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->data);
}
}
// 层序遍历
void levelorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
TreeNode** queue = (TreeNode**)malloc(sizeof(TreeNode*) * 1000);
int front = 0, rear = 0;
queue[rear++] = root;
while (front != rear) {
TreeNode* node = queue[front++];
printf("%d ", node->data);
if (node->left != NULL) {
queue[rear++] = node->left;
}
if (node->right != NULL) {
queue[rear++] = node->right;
}
}
}
// 创建节点
TreeNode* createNode(int data) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 销毁节点
void destroyNode(TreeNode* node) {
if (node != NULL) {
free(node);
}
}
// 销毁二叉树
void destroyTree(TreeNode* root) {
if (root != NULL) {
destroyTree(root->left);
destroyTree(root->right);
destroyNode(root);
}
}
int main() {
int preorder[] = { 1, 2, 4, 5, 3, 6 };
int inorder[] = { 4, 2, 5, 1, 3, 6 };
int length = sizeof(preorder) / sizeof(preorder[0]);
TreeNode* root = buildTree(preorder, inorder, 0, length - 1, 0, length - 1);
printf("前序遍历:");
preorderTraversal(root);
printf("\n中序遍历:");
inorderTraversal(root);
printf("\n后序遍历:");
postorderTraversal(root);
printf("\n层序遍历:");
levelorderTraversal(root);
printf("\n");
destroyTree(root);
return 0;
}
```
该代码实现了二叉树的构造、创建、遍历和销毁功能,可以根据前序和中序遍历构造二叉树,并且实现了四种遍历方式,同时也提供了创建和销毁节点的方法。
阅读全文