trie树
golang code:
package main
import (
"fmt"
)
// trie,根节点没有字符,然后每层一个字符, 前缀相同的是同一路径
// 如: test, team 有相同前缀 te, warm, warn 有相同前缀war
// __ root__
// / \
// t w
// / /
// e a
// / \ /
// s a r
// / \ / \
// t m m n
//
// 这个例子是通过 字符串,查找字符串对应的值
type Node struct {
Children map[byte]*Node // 子结点
Priority int
}
func NewNode() *Node {
return &Node{make(map[byte]*Node), 0}
}
type Trie struct {
Root *Node
}
func NewTrie() *Trie {
root := NewNode()
return &Trie{root}
}
func (t *Trie) Insert(str string, priority int) {
bytes := []byte(str)
current := t.Root
for i := 0; i < len(bytes); i++ {
char := bytes[i]
if node := current.Children[char]; node != nil {
current = node
} else {
newnode := NewNode()
current.Children[char] = newnode
current = newnode
}
}
current.Priority = priority
}
// 根据str, 查找其对应的priority
func (t *Trie) Find(str string) int {
bytes := []byte(str)
current := t.Root
fmt.Print("find ")
for i := 0; i < len(bytes); i++ {
char := bytes[i]
fmt.Print(string(char))
if node := current.Children[char]; node == nil {
fmt.Println(": not found")
return -1
} else {
current = node
}
}
priority := current.Priority
fmt.Println(", priority: ", priority)
return priority
}
func main() {
words := []string{"test", "team", "space", "work", "missing", "illegal", "go", "golang"}
priority := []int{4, 5, 6, 7, 8, 9, 10, 11}
trie := NewTrie()
// 建trie树
for i := 0; i < len(words); i++ {
trie.Insert(words[i], priority[i])
}
// 查找
trie.Find("test")
trie.Find("team")
trie.Find("space")
trie.Find("work")
trie.Find("missing")
trie.Find("illegal")
trie.Find("go")
trie.Find("golang")
}
// 输出 find test, priority: 4 find team, priority: 5 find space, priority: 6 find work, priority: 7 find missing, priority: 8 find illegal, priority: 9 find go, priority: 10 find golang, priority: 11 成功: 进程退出代码 0.

浙公网安备 33010602011771号