#include <stdio.h>
#include <stdlib.h>
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
// 创建二叉树
TreeNode* createTree() {
int val;
printf("Enter the node value (-1 for null): ");
scanf("%d", &val);
if (val == -1) {
return NULL;
}
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = createTree();
node->right = createTree();
return node;
}
// 先序遍历二叉树
void preOrder(TreeNode *root) {
if (root != NULL) {
printf("%d ", root->val);
preOrder(root->left);
preOrder(root->right);
}
}
// 中序遍历二叉树
void inOrder(TreeNode *root) {
if (root != NULL) {
inOrder(root->left);
printf("%d ", root->val);
inOrder(root->right);
}
}
// 后序遍历二叉树
void postOrder(TreeNode *root) {
if (root != NULL) {
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->val);
}
}
// 查找二叉树中是否包含指定值
TreeNode* search(TreeNode *root, int val) {
if (root == NULL || root->val == val) {
return root;
}
TreeNode *left = search(root->left, val);
if (left != NULL) {
return left;
}
return search(root->right, val);
}
// 插入节点
void insert(TreeNode **root, int val) {
if (*root == NULL) {
TreeNode *node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
*root = node;
} else if (val < (*root)->val) {
insert(&((*root)->left), val);
} else {
insert(&((*root)->right), val);
}
}
// 查找并删除节点
TreeNode* delete(TreeNode *root, int val) {
if (root == NULL) {
return NULL;
}
if (val < root->val) {
root->left = delete(root->left, val);
} else if (val > root->val) {
root->right = delete(root->right, val);
} else {
if (root->left == NULL) {
TreeNode *right = root->right;
free(root);
return right;
} else if (root->right == NULL) {
TreeNode *left = root->left;
free(root);
return left;
} else {
TreeNode *min = root->right;
while (min->left != NULL) {
min = min->left;
}
root->val = min->val;
root->right = delete(root->right, min->val);
}
}
return root;
}
int main() {
// 创建二叉树
TreeNode *root = createTree();
// 先序遍历二叉树
printf("Preorder traversal: ");
preOrder(root);
printf("\n");
// 中序遍历二叉树
printf("Inorder traversal: ");
inOrder(root);
printf("\n");
// 后序遍历二叉树
printf("Postorder traversal: ");
postOrder(root);
printf("\n");
// 查找节点
TreeNode *node = search(root, 3);
if (node != NULL) {
printf("Node with value 3 found in the tree.\n");
} else {
printf("Node with value 3 not found in the tree.\n");
}
// 插入节点
insert(&root, 5);
printf("Inorder traversal after insertion of 5: ");
inOrder(root);
printf("\n");
// 删除节点
root = delete(root, 3);
printf("Inorder traversal after deletion of 3: ");
inOrder(root);
printf("\n");
return 0;
}
/*这个代码实现了二叉树的创建、遍历、查找、插入和删除等基本操作。
注意,在插入和删除节点时,我们需要通过传递指向指针的指针来实现对二叉树的修改。
*/
C语言实现二叉树
最新推荐文章于 2024-10-18 16:49:59 发布