编写一个程序实现二叉树的各种基本运算的c语言程序
时间: 2023-09-30 11:06:03 浏览: 99
以下是一个简单的二叉树的c语言程序,实现了插入节点、删除节点、查找节点、遍历节点等基本运算:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
// 创建新节点
TreeNode* new_node(int data) {
TreeNode* node = (TreeNode*) malloc(sizeof(TreeNode));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
// 插入节点
TreeNode* insert_node(TreeNode* node, int data) {
if (node == NULL) {
return new_node(data);
}
if (data < node->data) {
node->left = insert_node(node->left, data);
} else if (data > node->data) {
node->right = insert_node(node->right, data);
}
return node;
}
// 删除节点
TreeNode* delete_node(TreeNode* node, int data) {
if (node == NULL) {
return node;
}
if (data < node->data) {
node->left = delete_node(node->left, data);
} else if (data > node->data) {
node->right = delete_node(node->right, data);
} else {
if (node->left == NULL) {
TreeNode* temp = node->right;
free(node);
return temp;
} else if (node->right == NULL) {
TreeNode* temp = node->left;
free(node);
return temp;
}
TreeNode* temp = node->right;
while (temp->left != NULL) {
temp = temp->left;
}
node->data = temp->data;
node->right = delete_node(node->right, temp->data);
}
return node;
}
// 查找节点
TreeNode* search_node(TreeNode* node, int data) {
if (node == NULL || node->data == data) {
return node;
}
if (data < node->data) {
return search_node(node->left, data);
} else {
return search_node(node->right, data);
}
}
// 中序遍历节点
void inorder_traversal(TreeNode* node) {
if (node == NULL) {
return;
}
inorder_traversal(node->left);
printf("%d ", node->data);
inorder_traversal(node->right);
}
int main() {
TreeNode* root = NULL;
root = insert_node(root, 50);
insert_node(root, 30);
insert_node(root, 20);
insert_node(root, 40);
insert_node(root, 70);
insert_node(root, 60);
insert_node(root, 80);
printf("Inorder traversal of the binary tree is: ");
inorder_traversal(root);
printf("\nDelete 20\n");
root = delete_node(root, 20);
printf("Inorder traversal of the modified binary tree is: ");
inorder_traversal(root);
printf("\nDelete 30\n");
root = delete_node(root, 30);
printf("Inorder traversal of the modified binary tree is: ");
inorder_traversal(root);
printf("\nDelete 50\n");
root = delete_node(root, 50);
printf("Inorder traversal of the modified binary tree is: ");
inorder_traversal(root);
return 0;
}
```
阅读全文