(三叉字典树)二叉树套字典树

看了道题,是要写个字典树排序的,但又不局限于二十六个字母,于是来了个三叉字典树(二叉树套字典树)。最差时间复杂度是trie树的常数倍,空间比trie树省得多了。

#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef struct Node
{
	char ch;
	int count;
	Node *lson, *rson, *subtree;
}Node ,*Nodelink;

Nodelink create(char ch)
{
	Nodelink p = new Node;
	p->ch = ch;
	p->lson = NULL;
	p->rson = NULL;
	p->subtree = NULL;
	p->count = 0;
	return p;
}
Nodelink root = create('\0');
void insert(char str[])
{
	int i;
	Nodelink p = root;
	for(i = 0; i < strlen(str); i++)
	{
               if(p->subtree == NULL)p->subtree = create('str[i]');
		p = p->subtree;
		while(p->ch != str[i])
		{
			if(str[i] < p->ch)
			{
				if(p->lson == NULL)p->lson = create(str[i]);
				p = p->lson;
			}
			else 
			{
				if(p->rson == NULL)p->rson = create(str[i]);
				p = p->rson;
			}
		}
		
	}
	p->count ++;
}
char pp[44];
void dfs(int top, Nodelink p)
{
	int i;
	if(p->lson != NULL)
		dfs(top, p->lson);
        pp[top] = p->ch;
        for(i = 0; i < p->count; i++)
	{
		pp[top + 1] = '\0';
		printf("%s\n", pp);
	}
	if(p->subtree != NULL)		
		dfs(top + 1, p->subtree);
	if(p->rson != NULL)
		dfs(top, p->rson);
}
Nodelink destroy(Nodelink p)
{
	if(p->lson != NULL)
		p->lson = destroy(p->lson);
	if(p->subtree != NULL)
		p->subtree = destroy(p->subtree);
	if(p->rson != NULL)
		p->rson = destroy(p->rson);
	delete p;
	return NULL;

}
int main()
{
	char str[33];
	freopen("test.in", "r", stdin);
	while(~scanf("%s", str))
	{
		insert(str);
	}
		dfs(0, root);
		destroy(root);
	return 0;
}


你可能感兴趣的:(数据结构)