algorithm - lookup tree with closest path prefix fallback

佐手、 提交于 2019-12-12 02:44:28

问题


I am after an algorithm for a problem where I maintain a tree structure on which I need to find the closest match for a data node. If no exact match, it falls back to the closest prefix.

For example, if say I have the below structure, where the words (number in words) are the branches and the numbers with square brackets are data (leaf node); I am after an algorithm that would come back with the set of results as shown in table below. Please note that the path separator is ">"

           one - [1]
            /\
         two  five
         /\       \
    eight  [12]    nine
   /                  \
 [128]                [159]


+---------------------------+--------+---------------------------------------------+
| path                      | result |                                             |
+---------------------------+--------+---------------------------------------------+
| one > five > nine         |    159 | whole path matches                          |
| one > five                |      1 | partial (only "one" matched)                |
| one > two > eight         |    128 | whole path matches                          |
| one > two                 |     12 | whole path matches                          |
| one > two > eight > seven |    128 | partial (only "one > two > eight" matched)  |
| one > two > seven         |     12 | partial (only "one > two" matched)          |
+---------------------------+--------+---------------------------------------------+

I am really after a C++ ( STL or boost based ) library; but just pointers to a nifty algorithm for this purpose would be equally good.


回答1:


You're looking for a Ternary Search Tree

http://en.wikipedia.org/wiki/Ternary_search_tree



来源:https://stackoverflow.com/questions/19120928/algorithm-lookup-tree-with-closest-path-prefix-fallback

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!