C语言二叉树的基本操作代码(含详细注释)
时间: 2023-05-19 17:05:14 浏览: 121
以下是C语言二叉树的基本操作代码,包括插入、删除、查找、遍历等操作,每个函数都有详细的注释说明:
//定义二叉树结构体
typedef struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
} TreeNode;
//插入节点
TreeNode* insert(TreeNode* root, int val) {
//如果根节点为空,则新建一个节点作为根节点
if (root == NULL) {
TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
//如果插入的值小于根节点的值,则插入到左子树中
if (val < root->val) {
root->left = insert(root->left, val);
}
//如果插入的值大于等于根节点的值,则插入到右子树中
else {
root->right = insert(root->right, val);
}
return root;
}
//删除节点
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* 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->val = temp->val;
root->right = delete(root->right, temp->val);
}
}
return root;
}
//查找节点
TreeNode* search(TreeNode* root, int val) {
if (root == NULL || root->val == val) {
return root;
}
if (val < root->val) {
return search(root->left, val);
}
else {
return search(root->right, val);
}
}
//前序遍历
void preorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
printf("%d ", root->val);
preorderTraversal(root->left);
preorderTraversal(root->right);
}
//中序遍历
void inorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
//后序遍历
void postorderTraversal(TreeNode* root) {
if (root == NULL) {
return;
}
postorderTraversal(root->left);
postorderTraversal(root->right);
printf("%d ", root->val);
}
//测试代码
int main() {
TreeNode* root = NULL;
root = insert(root, 5);
root = insert(root, 3);
root = insert(root, 7);
root = insert(root, 1);
root = insert(root, 9);
root = insert(root, 4);
root = insert(root, 6);
printf("前序遍历:");
preorderTraversal(root);
printf("\n");
printf("中序遍历:");
inorderTraversal(root);
printf("\n");
printf("后序遍历:");
postorderTraversal(root);
printf("\n");
root = delete(root, 3);
printf("删除节点3后的中序遍历:");
inorderTraversal(root);
printf("\n");
TreeNode* node = search(root, 7);
if (node != NULL) {
printf("查找节点7成功!\n");
}
else {
printf("查找节点7失败!\n");
}
return 0;
}
阅读全文