您的位置:首页 > 理论基础 > 数据结构算法

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

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

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<vector>
#include<cmath>
#include<string>
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息