C语言实现根据key值进行二叉树的增删查改
时间: 2024-05-05 22:16:19 浏览: 68
1. 增加节点:
```c
struct TreeNode* insert(struct TreeNode* root, int key) {
if (root == NULL) {
return createNode(key);
}
if (key < root->key) {
root->left = insert(root->left, key);
} else if (key > root->key) {
root->right = insert(root->right, key);
}
return root;
}
```
2. 删除节点:
```c
struct TreeNode* delete(struct TreeNode* root, int key) {
if (root == NULL) {
return root;
}
if (key < root->key) {
root->left = delete(root->left, key);
} else if (key > root->key) {
root->right = delete(root->right, key);
} 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;
}
struct TreeNode* temp = minValueNode(root->right);
root->key = temp->key;
root->right = delete(root->right, temp->key);
}
return root;
}
```
3. 查找节点:
```c
struct TreeNode* search(struct TreeNode* root, int key) {
if (root == NULL || root->key == key) {
return root;
}
if (key < root->key) {
return search(root->left, key);
}
return search(root->right, key);
}
```
4. 修改节点:
```c
struct TreeNode* modify(struct TreeNode* root, int oldKey, int newKey) {
root = delete(root, oldKey);
root = insert(root, newKey);
return root;
}
```
阅读全文