二叉排序/搜索树类模板

二叉排序树类模板

模板类

将整个二叉排序树封装为一个模板类
刚开始用静态变量当函数参数默认参数,但所有对象共用一个变量就没办法保存多个树的root了。解决办法是:把递归的函数设为私有函数。然后用一个公用的函数去调用这个函数,同时给这个函数传值。这样用户就可以直接调用函数,而不需要传任何值。

#include <iostream>
#include<vector>
#include<queue>
using namespace std;
template<typename T>
//luosansui
class TreeNode {
   
public:
	T value;
	TreeNode* left;
	TreeNode* right;
	TreeNode(const T& value) {
   
		this->value = value;
		left = NULL;
		right = NULL;
	}
};
//默认比较规则
class Compare {
   
public:
	bool operator()(int a, int b) {
   
		return a < b;
	}
	bool operator()(char a, char b) {
   
		return a < b;
	}
	bool operator()(float a, float b) {
   
		return a < b;
	}
	bool operator()(double a, double b) {
   
		return a < b;
	}
};
template<typename T, typename Tclass = Compare>
//二叉查找树
class BinarySortTree {
   
private:
	TreeNode<T>* root;
	TreeNode<T>* nullp;
	Tclass compare;
	//记录节点数目
	int node_num;
	//查找
	TreeNode<T>*& _findData(const T& node_value, TreeNode<T>*& node) {
   
		if (node == NULL) {
   
			return nullp;
		}
		else if (node_value == node->value) {
   
			return node;
		}
		if (!compare(node_value, node->value)) {
   
			return _findData(node_value, node->right);
		}
		else {
   
			return _findData(node_value, node->left);
		}
	}
	//析构用的遍历
	void _destruct(TreeNode<T>*& node) {
   
		if (node == NULL)return;
		_destruct(node->left);
		_destruct(node->right);
		delete node;
	}
	//打印
	void _print(TreeNode<T>*& node) {
   
		if (node == NULL)return;
		_print(node->
  • 10
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值