用C++解决一个问题,问题如下,设计一个算法,它从二叉检索树中删除一个人工输入的结点,并仍然保持二叉检索树的特性不变。
时间: 2024-03-07 07:47:07 浏览: 55
好的,这里是一个简单的C++代码实现,可以让用户自己输入要删除的值:
```c++
#include <iostream>
using namespace std;
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
TreeNode* deleteNode(TreeNode* root, int key) {
if (root == NULL) return root;
if (key < root->val) {
root->left = deleteNode(root->left, key);
} else if (key > root->val) {
root->right = deleteNode(root->right, key);
} else {
if (root->left == NULL) {
TreeNode* temp = root->right;
delete root;
return temp;
} else if (root->right == NULL) {
TreeNode* temp = root->left;
delete root;
return temp;
} else {
TreeNode* temp = root->right;
while (temp->left != NULL) {
temp = temp->left;
}
root->val = temp->val;
root->right = deleteNode(root->right, temp->val);
}
}
return root;
}
void inorder(TreeNode* root) {
if (root == NULL) return;
inorder(root->left);
cout << root->val << " ";
inorder(root->right);
}
int main() {
TreeNode* root = new TreeNode(5);
root->left = new TreeNode(3);
root->right = new TreeNode(6);
root->left->left = new TreeNode(2);
root->left->right = new TreeNode(4);
root->right->right = new TreeNode(7);
cout << "Before deletion: ";
inorder(root);
cout << endl;
int key;
cout << "Enter the value of node to be deleted: ";
cin >> key;
root = deleteNode(root, key);
cout << "After deletion: ";
inorder(root);
cout << endl;
return 0;
}
```
该算法的时间复杂度为O(h),其中h是二叉搜索树的高度。在最坏的情况下,h可以达到O(n),其中n是树的结点数,因此,该算法的最坏时间复杂度为O(n)。
阅读全文