我的理解是用来做字符串搜索的,每个节点只包含一个字符,比如录入单词world,则树的结构是:
这时再录入单词worab,则树的结构为:
所以每个节点必须还要一个字段is_end标识是否为结束单词。比如用户输入wor,搜索所有wor开头的单词,假设现在有一个单词就是wor,从w开始检索,当检索到r的时候需要判断r节点的is_end为true,则把wor加入到结果列表,然后继续往下面检索。
php实现代码:
searchchildnode($value); if(empty($node)){ // 不存在节点,添加为子节点 $node = new node(); $node->value = $value; $this->childnode[] = $node; } $node->is_end = $is_end; return $node; } /* 查询子节点 */ public function searchchildnode($value){ foreach ($this->childnode as $k => $v) { if($v->value == $value){ // 存在节点,返回该节点 return $this->childnode[$k]; } } return false; }}/* 添加字符串 */function addstring(&$head, $str){ $node = null; for ($i=0; $i addchildnode($str[$i], $is_end); }else{ $node = $node->addchildnode($str[$i], $is_end); } } }}/* 获取所有字符串--递归 */function getchildstring($node, $str_array = array(), $str = ''){ if($node->is_end == true){ $str_array[] = $str; } if(empty($node->childnode)){ return $str_array; }else{ foreach ($node->childnode as $k => $v) { $str_array = getchildstring($v, $str_array, $str . $v->value); } return $str_array; }}/* 搜索 */function searchstring($node, $str){ for ($i=0; $i searchchildnode($str[$i]); // print_r($node); if(empty($node)){ // 不存在返回空 return false; } } } return getchildstring($node);}/* 调用测试开始 */$head = new node; // 树的head// 添加单词addstring($head, 'hewol');addstring($head, 'hemy');addstring($head, 'heml');addstring($head, 'you');addstring($head, 'yo');// 获取所有单词$str_array = getchildstring($head);// 搜索$search_array = searchstring($head, 'hem');// 循环打印所有搜索结果foreach ($search_array as $key => $value) { echo 'hem' . $value . '
'; // 输出带上搜索前缀}
以上就介绍了字 php实现trie树(字典树),包括了字方面的内容,希望对php教程有兴趣的朋友有所帮助。
