描述
删除给定键值的树结点,并维护二叉搜索树的特性。即它的每个结点的值都大于其左子树上的所有结点的值,并且小于其右子树上所有结点的值。
需要分多个情况考虑:
1.当结点没有左子树(或右子树)时:这时候直接把右子树(或左子树)(即使为空也没有关系)替换当前结点返回,并释放当前结点的空间。
具体操作代码:
if(node->left == NULL) {
Node* rightNode = node->right;
count--;
delete node;
return rightNode;
}
else if(node->right == NULL) {
Node* leftNode = node->left;
count--;
delete node;
return leftNode;
}
2.当结点拥有左右子树时:可以把右子树的最小值或左子树的最大值换到当前位置,这将依然满足二叉搜索树的定义。
具体操作代码:
//找到左子树的最大值结点
Node* now = new Node(searchMax(node->left));
//新增一个结点
count++;
now->left = removeMax(node->left);
now->right = node->right;
delete node;
count--;
return now;
完整实现代码
二叉搜索树的基本操作实现。
#include<iostream>
#include<queue>
using namespace std;
template<class Key, class Value>
class BinarySearchTree {
private:
struct Node {
Key key;
Value value;
Node *left;
Node *right;
Node(Key k, Value v) {
this->key = k;
this->value = v;
this->left = NULL;
this->right = NULL;
}
Node(Node* node) {
this->key = node->key;
this->value = node->value;
this->left = node->left;
this->right = node->right;
}
};
Node *root;
int count;
public:
BinarySearchTree() {
root = NULL;
count = 0;
}
~BinarySearchTree() {
destroy(root);
}
int size() {
return count;
}
int isEmpty