用C语言写出二叉树的各种使用方法
时间: 2024-02-19 08:58:16 浏览: 78
用C++实现二叉树的建立,删除,添加。主要使用的是类的结构。....rar
二叉树是一种常用的数据结构,可以用来存储和处理数据。下面是一些用C语言实现二叉树的常用方法:
1. 创建二叉树:
```
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createTree(int val) {
struct TreeNode *node = malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
```
2. 插入节点:
```
void insertNode(struct TreeNode *root, int val) {
if (root == NULL) {
root = createTree(val);
return;
}
if (val < root->val) {
if (root->left == NULL) {
root->left = createTree(val);
} else {
insertNode(root->left, val);
}
} else {
if (root->right == NULL) {
root->right = createTree(val);
} else {
insertNode(root->right, val);
}
}
}
```
3. 删除节点:
```
struct TreeNode* deleteNode(struct TreeNode *root, int val) {
if (root == NULL) {
return NULL;
}
if (val < root->val) {
root->left = deleteNode(root->left, val);
} else if (val > root->val) {
root->right = deleteNode(root->right, val);
} else {
if (root->left == NULL && root->right == NULL) {
free(root);
return NULL;
} else if (root->left == NULL) {
struct TreeNode *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct TreeNode *temp = root->left;
free(root);
return temp;
} else {
struct TreeNode *temp = findMin(root->right);
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
}
return root;
}
struct TreeNode* findMin(struct TreeNode *node) {
while (node->left != NULL) {
node = node->left;
}
return node;
}
```
4. 查找节点:
```
struct TreeNode* searchNode(struct TreeNode *root, int val) {
if (root == NULL || root->val == val) {
return root;
}
if (val < root->val) {
return searchNode(root->left, val);
} else {
return searchNode(root->right, val);
}
}
```
5. 中序遍历:
```
void inorderTraversal(struct TreeNode *root) {
if (root != NULL) {
inorderTraversal(root->left);
printf("%d ", root->val);
inorderTraversal(root->right);
}
}
```
以上是二叉树的常用方法,可以根据实际需求进行修改和扩展。
阅读全文