(三叉字典树)二叉树套字典树
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; }
相关文章推荐
- 【二叉树】字典树
- 数据结构-树(多叉树、二叉树、二叉搜索树、平衡二叉树、字典树、红黑树、线段树)
- POJ1056_IMMEDIATE DECDABILITY_二叉树搜索||字典树
- 二叉树 字典树
- 算法导论第十章习题10.4-3非递归方式实现二叉树的中序遍历
- 判断是否是轴对称二叉树
- 遍历二叉树的各种操作
- 《剑指offer》——二叉树的下一个结点
- 二叉树(二)——递归遍历
- C++基于先序、中序遍历结果重建二叉树的方法
- 根据中序序列与后序序列构建二叉树
- hdu1671Phone List - 字典树
- 二叉树之先序建立二叉树
- 数据结构:二叉树的访问--广度优先遍历法
- 二叉树建立和遍历
- 【数据结构1】(查询二叉树的实现)
- 二叉树练习代码
- 数据结构-二叉树的存储结构与遍历
- 把一个有序的数组转为二叉树存储
- [学习笔记]二叉树的线索化和遍历