#include <iostream>
#include <cstdlib>
template<typename E, typename K>
struct BSTNode {
E data;
BSTNode<E, K> *left, *right;
BSTNode(): left(NULL), right(NULL) {}
BSTNode(const E d, BSTNode<E, K> *l = NULL, BSTNode<E, K> *r = NULL)
: data(d), left(l), right(r) {}
~BSTNode() {}
void set_data(E d) { data = d; }
E get_data() { return data; }
};
template<typename E, class K>
class BSTree {
public:
BSTree(): root(NULL) {}
BSTree(K value);
~BSTree() {}
bool search(const K x) const {
return (search(x, root) != NULL);
}
BSTree<E, K>& operator=(const BSTree<E, K>& t);
void make_empty() {
make_empty(root);
root = NULL;
}
void print_tree() const { print_tree(root); }
E min() { return min(root)->data; }
E max() { return max(root)->data; }
bool insert(const E& e) { return insert(e, root); }
bool remove(const K x) { return remove(x, root); }
private:
BSTNode<E, K> *root;
K refvalue;
BSTNode<E, K> *search(const K x, BSTNode<E, K> *ptr);
void make_empty(BSTNode<E, K> *& ptr);
void print_tree(BSTNode<E, K> *ptr) const;
BSTNode<E, K> *copy(const BSTNode<E, K> *ptr);
BSTNode<E, K> *min(BSTNode<E, K> *ptr) const;
BSTNode<E, K> *max(BSTNode<E, K> *ptr) const;
bool insert(const E& e, BSTNode<E, K> *& ptr);
bool remove(const K x, BSTNode<E, K> *& ptr);
};
template<typename E, typename K>
BSTNode<E, K> *BSTree<E, K>::search(const K x, BSTNode<E, K> *ptr) {
if (ptr == NULL)
return NULL;
else if (x < ptr->data)
return search(x, ptr->left);
else if (x > ptr->data)
return search(x, ptr->right);
else return ptr;
}
template<typename E, class K>
bool BSTree<E, K>::insert(const E& e, BSTNode<E, K>*& ptr) {
if (ptr == NULL) {
ptr = new BSTNode<E, K>(e);
if (ptr == NULL) {
std::cerr << "out of space " << std::endl;
exit(1);
}
return true;
}
else if (e < ptr->data)
insert(e, ptr->left);
else if (e > ptr->data)
insert(e, ptr->right);
else return false;
}
template<typename E, typename K>
BSTree<E, K>::BSTree(K value) {
E x;
root = NULL;
refvalue = value;
std::cin >> x;
while (x.key != refvalue) {
insert(x, root);
std::cin >> x;
}
}
template<typename E, typename K>
bool BSTree<E, K>::remove(const K x, BSTNode<E, K>*& ptr) {
BSTNode<E, K> *temp;
if (ptr != NULL) {
if (x < ptr->data)
remove(x, ptr->left);
else if (x > ptr->data)
remove(x, ptr->right);
else if (ptr->left != NULL && ptr->right != NULL) {
temp = ptr->right;
while (temp->left != NULL)
temp = temp->left;
ptr->data = temp->data;
remove(ptr->data, ptr->right);
}
else {
temp = ptr;
if (ptr->left == NULL)
ptr = ptr->right;
else ptr = ptr->left;
delete temp;
return true;
}
}
}
BinarySearchTree
最新推荐文章于 2023-11-03 09:13:13 发布