用C++解决一个问题,问题如下,设计一个算法,它从二叉检索树中删除一个结点,并仍然保持二叉检索树的特性不变。
时间: 2024-03-07 13:47:03 浏览: 82
好的,这是一个经典的二叉搜索树删除问题,下面是一个简单的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;
root = deleteNode(root, 3);
cout << "After deletion: ";
inorder(root);
cout << endl;
return 0;
}
```
该算法的时间复杂度为O(h),其中h是二叉搜索树的高度。在最坏的情况下,h可以达到O(n),其中n是树的结点数,因此,该算法的最坏时间复杂度为O(n)。
阅读全文