Trie

In computer science, a trie, also called digital tree and sometimes radix tree or prefix tree (as they can be searched by prefixes), is an ordered tree data structure that is used to store a dynamic set or associative array where the keys are usually strings. Unlike a binary search tree, no node in the tree stores the key associated with that node; instead, its position in the tree defines the key with which it is associated. All the descendants of a node have a common prefix of the string associated with that node, and the root is associated with the empty string. Values are normally not associated with every node, only with leaves and some inner nodes that correspond to keys of interest. 

基数树(Radix Tree).   基数树(Radix Tree)

A trie for keys "A", "to", "tea", "ted", "ten", "i", "in", and "inn"                An example of a radix tree

Radix Tree

In computer science, a radix tree (also patricia trie, radix trieor compact prefix tree) is a data structure that represents a space-optimized trie in which each node with only one child is merged with its parent. 

 

基数树(Radix Tree)基数树(Radix Tree)

基数树(Radix Tree)基数树(Radix Tree)

 

Integer Trie

Trie树可以存储位串(stirngs of bits),因为整数可以用二进制表示,故Trie树可以存储整数.如Figure 5.2所示,串0011,011,11表示不同的位串,但却表示同一个整数3,这就是问题所在!解决方法就是使用小端整数(右边的权重高),这样3是(11)2,2是(01)2.

python实现Figure 5.3:

#!/usr/bin/python
#-*- coding:utf-8 -*-
class Node:
    def __init__(self):
        self.left = self.right = None
        self.value = None


def TrieInsert(t, key,value = None):
    if t is None:
        t = Node()
    p = t
    while key != 0:
        if key & 1==0:
            if p.left is None:
                p.left = Node()
            p = p.left
        else:
            if p.right is None:
                p.right = Node()
            p = p.right
        key =key>>1
    p.value = value
    return t

def Lookup(t,key):
    while key != 0 and (t is not None):
        if key & 1 == 0:
            t = t.left
        else:
            t = t.right
        key = key>>1
    if t is not None:
        return t.value
    else:
        return None

def main():
    t = Node()
    TrieInsert(t, 1, 'a')
    TrieInsert(t, 4 ,'b')
    TrieInsert(t, 5, 'c')
    TrieInsert(t, 9, 'd')
    print Lookup(t,9)


if __name__ == "__main__":
    main()
View Code

相关文章:

  • 2021-11-23
  • 2021-05-04
  • 2021-11-20
  • 2022-12-23
  • 2021-09-28
  • 2022-03-06
猜你喜欢
  • 2021-07-26
  • 2022-12-23
  • 2021-12-13
  • 2021-05-24
  • 2021-06-19
  • 2022-12-23
相关资源
相似解决方案