Algorithm第四版算法 C++实现(二十五)——单词查找树(基于单词查找树的符号表,基于三向查找树的符号表)

基于单词查找树的符号表

这种方法其实也很简单,我们把每个节点都设置256个子节点,然后将字符串往里面插入就行了

/*基于单词查找树的符号表*/
template<typename V>
class trie
{
private:
	const static int r = 256;
	struct node
	{
		V value;
		node next[r];
	} *root;
	node *get(node *x, std::string key, int d)
	{
		if (x == nullptr)
			return nullptr;
		if (d == key.length())
			return x;
		char c = key[d];
		return get(x->next[d], key, d + 1);
	}
	node *put(node *x, std::string key, V value, int d)
	{
		if (x == nullptr)
		{
			x = new node;
		}
		if (d == key.length())
		{
			x->value = value;
			return x;
		}
		char c = key[d];
		x->next[c] = put(x.next[c], key, value, d + 1);
		return x;
	}
public:
	V get(std::string key)
	{
		node *x = get(root, key, 0);
		if (x == nullptr)
			return NULL;
		return x->value;
	}
	void put(std::string key, V value)
	{
		root = put(root, key, value, 0);
	}
};

基于三向查找树的符号表

关于三向xxx我们已经遇到很多了,相信你一看就能明白什么意思

/*基于三向查找树的符号表*/
template<typename V>
class TST
{
private:
	struct  node
	{
		char c;
		node *left, *right, *mid;
		V value;
	} *root;
	node *get(node *x, std::string key, int d)
	{
		if (x == nullptr)
			return nullptr;
		char c = key[d];
		if (c < x->c)
			return get(x->left, key, d);
		else if (c < x->c)
			return get(x->right, key, d);
		else if (d < key.length() - 1)
			return get(x->mid, key, d + 1);
		else 
			return x;
	}
	node *put(node x, std::string key, V value, int d)
	{
		char c = key[d];
		if (x == nullptr)
		{
			x = new node;
			x->c = c;
		}
		if (c < x->c)
			x->left = put(x->left, key, value, d);
		else if (c > x->c)
			x->right = put(x->right, key, value, d);
		else
			x->value = value;
		return x;
	}
public:
	V get(std::string key)
	{
		node *x = get(root, key, 0);
		if (x == nullptr)
			return NULL;
		return x->value;
	}
	void put(std::string key, V value)
	{
		root = put(root, key, value, 0);
	}
};

值得注意的是,虽然单词查找树符号表比起三向查找树符号表要矮很多,这就意味着要更快,但是我们同时也必须注意到单词查找树的复杂难以整理及其浪费的大量内存。我个人是更倾向于使用第二种方法的

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值