二叉树的增删改查 c语言
时间: 2023-09-07 14:13:43 浏览: 66
好的,下面是二叉树的增删改查的C语言代码示例。
首先,我们需要定义二叉树的结构体:
```c
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
```
接下来,我们分别实现二叉树的增、删、改、查操作:
1. 增加节点
```c
struct TreeNode* insertNode(struct TreeNode* root, int val) {
if (!root) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
if (val < root->val) {
root->left = insertNode(root->left, val);
} else if (val > root->val) {
root->right = insertNode(root->right, val);
}
return root;
}
```
2. 删除节点
```c
struct TreeNode* deleteNode(struct TreeNode* root, int key) {
if (!root) {
return NULL;
}
if (root->val == key) {
if (!root->left) {
struct TreeNode* tmp = root->right;
free(root);
return tmp;
} else if (!root->right) {
struct TreeNode* tmp = root->left;
free(root);
return tmp;
} else {
struct TreeNode* p = root->right;
while (p->left) {
p = p->left;
}
root->val = p->val;
root->right = deleteNode(root->right, p->val);
}
} else if (root->val > key) {
root->left = deleteNode(root->left, key);
} else {
root->right = deleteNode(root->right, key);
}
return root;
}
```
3. 修改节点
```c
struct TreeNode* modifyNode(struct TreeNode* root, int oldVal, int newVal) {
root = deleteNode(root, oldVal);
root = insertNode(root, newVal);
return root;
}
```
4. 查找节点
```c
struct TreeNode* searchNode(struct TreeNode* root, int val) {
if (!root || root->val == val) {
return root;
}
if (root->val > val) {
return searchNode(root->left, val);
} else {
return searchNode(root->right, val);
}
}
```
以上就是二叉树的增删改查的C语言代码示例。