#include <iostream>
#include <vector>
#include <ctime>
using namespace std;
template <typename Key, typename Value>
class BST {
private:
struct Node {
Key key;
Value value;
Node *left;
Node *right;
Node(Key key, Value value) {
this->key = key;
this->value = value;
this->left = this->right = nullptr;
}
};
public:
Node *root;
int count;
public:
BST() {
root = nullptr;
count = 0;
}
~BST() {
//do do
}
int size() {
return count;
}
bool isEmpty() {
return count == 0;
}
void insert(Key key, Value value) {
root = insert(root, key, value);
}
bool contain(Key key) {
return contain(root, key);
}
Value* search(Key key) {
return search(root, key);
}
//前序遍历
void preOrder() {
preOrder(root);
}
void inOrder() {
inOrder(root);
}
void postOrder() {
postOrder(root);
}
private:
//向以node为根的二叉搜索树中,插入节点(key, value)
//返回插入新节点后的二叉搜索树的根
Node* insert(Node* node, Key key, Value value) {
if (node == nullptr) {
count++;
return new Node(key, value);
}
if (key == node->key)
node->value = value;
else if (key < node->key)
node->left = insert(node->left, key, value);
else // key > node->key
node->right = insert(node->right, key, value);
return node;
}
// 查看以node为根的二叉搜索树中是否包含键值为key的节点
bool contain(Node* node, Key key) {
if (node == nullptr)
return false;
if (key == node->key)
return true;
else if (key < node->key)
return contain(node->left, key);
else
return contain(node->right, key);
}
Value* search(Node* node, Key key) {
if (node == nullptr)
return nullptr;
if (key == node->key)
return &(node->value);
else if (key < node->key)
return search(node->left, key);
else
return search(node->right, key);
}
// 对以node为根的二叉搜索树进行前序遍历
void preOrder(Node* root) {
if (root == nullptr)
return;
cout << root->key << " ";
preOrder(root->left);
preOrder(root->right);
}
// 对以node为根的二叉搜索树进行中序遍历
void inOrder(Node* root) {
if (root == nullptr)
return;
inOrder(root->left);
cout << root->key << " ";
inOrder(root->right);
}
// 对以node为根的二叉搜索树进行中序遍历
void postOrder(Node* root) {
if (root == nullptr)
return;
postOrder(root->left);
postOrder(root->right);
cout << root->key << " ";
}
};
int main()
{
srand(time(NULL));
BST<int, int> tree;
for (int i = 0; i < 20; ++i) {
tree.insert(rand() % (i + 1), rand() % (i + 2));
}
tree.inOrder();
cout << endl;
tree.preOrder();
cout << endl;
tree.postOrder();
cout << endl;
return 0;
}
二叉搜索树实现
最新推荐文章于 2024-10-15 21:35:53 发布