C++二叉排序树插入删除结点
时间: 2024-01-07 22:23:12 浏览: 89
以下是C++中二叉排序树插入和删除结点的示例代码:
1. 插入结点:
```cpp
// 定义二叉排序树结点
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
// 插入结点
void insertNode(TreeNode*& root, int val) {
if (root == nullptr) {
root = new TreeNode(val);
return;
}
if (val < root->val) {
insertNode(root->left, val);
} else {
insertNode(root->right, val);
}
}
```
2. 删除结点:
```cpp
// 删除结点
void deleteNode(TreeNode*& root, int val) {
if (root == nullptr) {
return;
}
if (val < root->val) {
deleteNode(root->left, val);
} else if (val > root->val) {
deleteNode(root->right, val);
} else {
if (root->left == nullptr && root->right == nullptr) {
delete root;
root = nullptr;
} else if (root->left == nullptr) {
TreeNode* temp = root;
root = root->right;
delete temp;
} else if (root->right == nullptr) {
TreeNode* temp = root;
root = root->left;
delete temp;
} else {
TreeNode* temp = findMin(root->right);
root->val = temp->val;
deleteNode(root->right, temp->val);
}
}
}
// 查找最小值结点
TreeNode* findMin(TreeNode* root) {
while (root->left != nullptr) {
root = root->left;
}
return root;
}
```
阅读全文