帮我用C语言写一段二叉树的代码
时间: 2024-05-05 11:16:06 浏览: 86
以下是一个简单的二叉树代码,可以实现插入节点、查找节点、删除节点等基本功能。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int data;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 插入节点
void insert(TreeNode **root, int data) {
if (*root == NULL) {
*root = malloc(sizeof(TreeNode));
(*root)->data = data;
(*root)->left = NULL;
(*root)->right = NULL;
} else {
if (data < (*root)->data) {
insert(&((*root)->left), data);
} else {
insert(&((*root)->right), data);
}
}
}
// 查找节点
TreeNode *find(TreeNode *root, int data) {
if (root == NULL) {
return NULL;
} else if (root->data == data) {
return root;
} else if (data < root->data) {
return find(root->left, data);
} else {
return find(root->right, data);
}
}
// 删除节点
TreeNode *delete(TreeNode *root, int data) {
if (root == NULL) {
return NULL;
} else if (data < root->data) {
root->left = delete(root->left, data);
} else if (data > root->data) {
root->right = delete(root->right, data);
} else {
if (root->left == NULL) {
TreeNode *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
TreeNode *temp = root->left;
free(root);
return temp;
} else {
TreeNode *temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->data = temp->data;
root->right = delete(root->right, temp->data);
}
}
return root;
}
// 中序遍历
void inorder(TreeNode *root) {
if (root != NULL) {
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
}
int main() {
TreeNode *root = NULL;
insert(&root, 5);
insert(&root, 3);
insert(&root, 7);
insert(&root, 1);
insert(&root, 4);
insert(&root, 6);
insert(&root, 8);
inorder(root);
printf("\n");
TreeNode *node = find(root, 4);
if (node != NULL) {
printf("Found %d\n", node->data);
} else {
printf("Not found\n");
}
root = delete(root, 7);
inorder(root);
printf("\n");
return 0;
}
```
阅读全文
相关推荐


















