二叉树的基本操作c语言
时间: 2023-06-11 17:08:45 浏览: 107
二叉树的基本操作(C语言实现)
二叉树是一种常见的数据结构,它的基本操作包括创建、插入、删除、遍历等。以下是二叉树的基本操作的C语言实现。
1. 创建二叉树
```c
#include <stdio.h>
#include <stdlib.h>
//定义二叉树结构体
typedef struct node {
int data;
struct node *left;
struct node *right;
} TreeNode, *Tree;
//创建二叉树
Tree createTree() {
Tree root = NULL;
int val;
scanf("%d", &val);
if (val != -1) {
root = (Tree)malloc(sizeof(TreeNode));
root->data = val;
root->left = createTree();
root->right = createTree();
}
return root;
}
```
2. 插入节点
```c
//插入节点
Tree insertNode(Tree root, int val) {
if (root == NULL) {
root = (Tree)malloc(sizeof(TreeNode));
root->data = val;
root->left = NULL;
root->right = NULL;
} else if (val < root->data) {
root->left = insertNode(root->left, val);
} else {
root->right = insertNode(root->right, val);
}
return root;
}
```
3. 删除节点
```c
//删除节点
Tree deleteNode(Tree root, int val) {
if (root == NULL) return NULL;
if (root->data == val) {
if (root->left == NULL && root->right == NULL) {
free(root);
root = NULL;
} else if (root->left == NULL) {
Tree temp = root;
root = root->right;
free(temp);
} else if (root->right == NULL) {
Tree temp = root;
root = root->left;
free(temp);
} else {
Tree temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
} else if (val < root->data) {
root->left = deleteNode(root->left, val);
} else {
root->right = deleteNode(root->right, val);
}
return root;
}
```
4. 遍历
```c
//前序遍历
void preOrder(Tree root) {
if (root == NULL) return;
printf("%d ", root->data);
preOrder(root->left);
preOrder(root->right);
}
//中序遍历
void inOrder(Tree root) {
if (root == NULL) return;
inOrder(root->left);
printf("%d ", root->data);
inOrder(root->right);
}
//后序遍历
void postOrder(Tree root) {
if (root == NULL) return;
postOrder(root->left);
postOrder(root->right);
printf("%d ", root->data);
}
```
以上就是二叉树的基本操作的C语言实现。
阅读全文