c语言实现二叉树各种操作并且包括主函数的完整代码
时间: 2024-04-16 16:04:48 浏览: 72
以下是一个简单的二叉树实现,包含插入、删除、查找、遍历等操作的完整代码,并附有主函数:
```c
#include <stdio.h>
#include <stdlib.h>
// 二叉树结构体
typedef struct BinaryTreeNode {
int data;
struct BinaryTreeNode *left, *right;
} TreeNode, *TreeNodePtr;
// 插入节点
void insertNode(TreeNodePtr *tree, int value) {
if (*tree == NULL) {
*tree = (TreeNodePtr) malloc(sizeof(TreeNode));
(*tree)->data = value;
(*tree)->left = NULL;
(*tree)->right = NULL;
} else if (value < (*tree)->data) {
insertNode(&((*tree)->left), value);
} else {
insertNode(&((*tree)->right), value);
}
}
// 查找节点
TreeNodePtr findNode(TreeNodePtr tree, int value) {
if (tree == NULL) {
return NULL;
} else if (value < tree->data) {
return findNode(tree->left, value);
} else if (value > tree->data) {
return findNode(tree->right, value);
} else {
return tree;
}
}
// 删除节点
TreeNodePtr deleteNode(TreeNodePtr tree, int value) {
TreeNodePtr temp;
if (tree == NULL) {
return NULL;
} else if (value < tree->data) {
tree->left = deleteNode(tree->left, value);
} else if (value > tree->data) {
tree->right = deleteNode(tree->right, value);
} else {
if (tree->left && tree->right) {
temp = findMin(tree->right);
tree->data = temp->data;
tree->right = deleteNode(tree->right, tree->data);
} else {
temp = tree;
if (tree->left == NULL) {
tree = tree->right;
} else if (tree->right == NULL) {
tree = tree->left;
}
free(temp);
}
}
return tree;
}
// 查找最小值
TreeNodePtr findMin(TreeNodePtr tree) {
if (tree == NULL) {
return NULL;
} else if (tree->left == NULL) {
return tree;
} else {
return findMin(tree->left);
}
}
// 中序遍历
void inorderTraversal(TreeNodePtr tree) {
if (tree != NULL) {
inorderTraversal(tree->left);
printf("%d ", tree->data);
inorderTraversal(tree->right);
}
}
// 先序遍历
void preorderTraversal(TreeNodePtr tree) {
if (tree != NULL) {
printf("%d ", tree->data);
preorderTraversal(tree->left);
preorderTraversal(tree->right);
}
}
// 后序遍历
void postorderTraversal(TreeNodePtr tree) {
if (tree != NULL) {
postorderTraversal(tree->left);
postorderTraversal(tree->right);
printf("%d ", tree->data);
}
}
int main() {
TreeNodePtr tree = NULL; // 初始化为空树
insertNode(&tree, 8);
insertNode(&tree, 3);
insertNode(&tree, 10);
insertNode(&tree, 1);
insertNode(&tree, 6);
insertNode(&tree, 14);
insertNode(&tree, 4);
insertNode(&tree, 7);
insertNode(&tree, 13);
printf("Inorder traversal: ");
inorderTraversal(tree);
printf("\n");
printf("Preorder traversal: ");
preorderTraversal(tree);
printf("\n");
printf("Postorder traversal: ");
postorderTraversal(tree);
printf("\n");
TreeNodePtr node = findNode(tree, 6);
if (node != NULL) {
printf("Found node: %d\n", node->data);
} else {
printf("Node not found.\n");
}
deleteNode(tree, 6);
printf("Inorder traversal after deletion: ");
inorderTraversal(tree);
printf("\n");
return 0;
}
```
这个例子创建了一个包含一些节点的二叉树,并演示了如何进行各种操作。
阅读全文