trie树其实是一种多叉树的应用,Trie树是用来解决,搜索引擎中,输入前缀能够给出提示词的很是好的解决方案node
在实现trie书算法之前,咱们先回顾温习下,多叉树的实现和遍历(对于咱们trie树的实现和便利帮助很大),这里就不说普通二叉树,由于原理同样,但相对简单算法
下面是算法实现,这个算法参考了<数据结构与算法分析>这本书中的描述和定义,用了一个很节省空间的结构定义数据结构
并无在父节点中存储全部的子节点,而是存储了节点的链表,通常叫作二叉链表法,这样算法看起来很是像二叉树了post
#include<stdio.h> #include<stdlib.h> #define maxsize 100 typedef struct node { char *data; struct node *first_child,*next_sibling;//fc是第一个孩子,nb是fc的临节点 } tree; /** a / \ \ b c d /\ \ e f g 建立出来的树结构如上 */ tree *insertTree(char *ch, tree *parent, tree *pre_sibling) { tree *child = (tree *)malloc(sizeof(tree)); child->data = ch; if (parent != NULL) parent->first_child = child; if (pre_sibling != NULL) pre_sibling->next_sibling = child; child->first_child = NULL; child->next_sibling = NULL; return child; } /**二叉链表建立树*/ tree *create() { //建立root节点 tree *root = (tree *)malloc(sizeof(tree)); root->data = "A"; root->first_child = NULL; root->next_sibling = NULL; /** * 建立多个子节点 **/ tree *b = insertTree("B", root, NULL); tree *c = insertTree("C", NULL, b); tree *g = insertTree("G", c, NULL); //tree *h = insertTree("H", g, NULL); tree *d = insertTree("D", NULL, c); tree *e = insertTree("E", b, NULL); tree *f = insertTree("F", NULL, e); return root; } void preOrder(tree *root) { printf("%c ",*root->data); if (root->first_child != NULL) { preOrder(root->first_child); } if (root->next_sibling != NULL) { preOrder(root->next_sibling); } } void postOrder(tree *root) { if (root->first_child != NULL) { postOrder(root->first_child); } printf("%c ",*root->data); if (root->next_sibling != NULL) { postOrder(root->next_sibling); } } int main() { tree *root = create(); printf("先序遍历:"); preOrder(root); printf("后序遍历:"); postOrder(root); }
最终结果搜索引擎
先序遍历:A B E F C G D 后序遍历:E F B G C D A [Finished in 0.2s]code
最后说一下数学之美中的一道题目,是按照层级遍历二叉树(固然能够推广到多叉树),这个之后再说吧,其实我一直在想若是数学之美中,这道题目不是限定的那么死,咱们彻底能够在数据结构上作文章,让这个问题变得很简单,就是在节点存储上同一层节点的链表,也算是借鉴了上面的一个结构描述索引