为什么trie也被称为“前缀树”?

时间:2013-09-28 09:36:21

标签: data-structures tree trie recursive-datastructures

我正在阅读维基百科上的this文章,偶然发现了“trie也被称为前缀树”这一行。

我知道trie的用法,但为什么称它为“前缀树”?

1 个答案:

答案 0 :(得分:2)

因为它们可以通过前缀搜索。您也可以反转trie并找到通配符:http://phpir.com/tries-and-wildcards

  

例如,学术一词将是c-i-m-e-d-a-c-a。使用相同的   以前的技术我们现在可以搜索以a结尾的所有单词   某个短语,允许我们在开头处理通配符   查询字词,例如* cademically。

<?php
function buildTries($words) {
        $trie = new Trie();
        $rtrie = new Trie();
        foreach($words as $word) {
                $trie->add($word);
                $rtrie->add(strrev($word));
        }
        return array('trie' => $trie, 'rtrie' => $rtrie);
}

function searchTries($search, $tries) {
        $terms = explode('*', $search);
        if(count($terms) > 2) {
                return false;
        }

        if(strlen($terms[0]) && strlen($terms[0])) {
                // middle wildcard
                $straight = $tries['trie']->prefixSearch($terms[0]);
                $rev = $tries['rtrie']->prefixSearch(strrev($terms[1]));
                return array_intersect($straight, reverseArray($rev));
        } else if(strlen($terms[1]) ) {
                // leading wildcard
                return reverseArray($tries['rtrie']->prefixSearch(strrev($terms[1])));
        } else {
                // trailing wildcard
                return $tries['trie']->prefixSearch($terms[0]);
        }
}

function reverseArray($keys) {
        $return = array();
        foreach($keys as $key => $value) {
                $return[strrev($key)] = $value;
        }
        return $return;
}

/* Do some searches */

$words = array( 
        'adder',
        'addled',
        'abject',
        'agreement',
        'astronaut',
        'handily', 
        'happily',
        'helpfully'
);
$tries = buildTries($words);

$return = searchTries('h*ly', $tries);
var_dump($return);

$return = searchTries('ha*ly', $tries);
var_dump($return);
?>

两个var转储的结果如下所示:

array(3) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
  ["helpfully"]=>
  NULL
}

array(2) {
  ["handily"]=>
  NULL
  ["happily"]=>
  NULL
}