用c语言编写一个二叉树
时间: 2023-12-07 17:02:59 浏览: 78
以下是一个简单的二叉树的C语言实现,包括插入、删除和查找节点的基本操作。
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;
TreeNode* createNode(int val) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
void insertNode(TreeNode** root, int val) {
if (*root == NULL) {
*root = createNode(val);
return;
}
if (val < (*root)->val) {
insertNode(&((*root)->left), val);
} else if (val > (*root)->val) {
insertNode(&((*root)->right), val);
}
}
TreeNode* findNode(TreeNode* root, int val) {
if (root == NULL || root->val == val) {
return root;
}
if (val < root->val) {
return findNode(root->left, val);
} else {
return findNode(root->right, val);
}
}
TreeNode* findMinNode(TreeNode* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}
void deleteNode(TreeNode** root, int val) {
if (*root == NULL) {
return;
}
if (val < (*root)->val) {
deleteNode(&((*root)->left), val);
} else if (val > (*root)->val) {
deleteNode(&((*root)->right), val);
} else {
if ((*root)->left == NULL && (*root)->right == NULL) {
free(*root);
*root = NULL;
} else if ((*root)->left == NULL) {
TreeNode* temp = *root;
*root = (*root)->right;
free(temp);
} else if ((*root)->right == NULL) {
TreeNode* temp = *root;
*root = (*root)->left;
free(temp);
} else {
TreeNode* minNode = findMinNode((*root)->right);
(*root)->val = minNode->val;
deleteNode(&((*root)->right), minNode->val);
}
}
}
void printTree(TreeNode* root) {
if (root != NULL) {
printTree(root->left);
printf("%d ", root->val);
printTree(root->right);
}
}
int main() {
TreeNode* root = NULL;
insertNode(&root, 5);
insertNode(&root, 3);
insertNode(&root, 7);
insertNode(&root, 1);
insertNode(&root, 4);
insertNode(&root, 6);
insertNode(&root, 8);
printf("Original tree: ");
printTree(root);
printf("\n");
deleteNode(&root, 1);
printf("After deleting 1: ");
printTree(root);
printf("\n");
deleteNode(&root, 7);
printf("After deleting 7: ");
printTree(root);
printf("\n");
deleteNode(&root, 5);
printf("After deleting 5: ");
printTree(root);
printf("\n");
return 0;
}
```
该程序的输出如下:
```
Original tree: 1 3 4 5 6 7 8
After deleting 1: 3 4 5 6 7 8
After deleting 7: 3 4 5 6 8
After deleting 5: 3 4 6 8
```
该二叉树示例中包含了插入节点、查找节点、删除节点和打印二叉树的基本操作。可以根据需要进行修改和扩展。
阅读全文