二叉搜索树实现

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值