-
Notifications
You must be signed in to change notification settings - Fork 26
/
trie.go
56 lines (49 loc) · 916 Bytes
/
trie.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package gbt2260
//节点
type Node struct {
value string
children map[string]*Node
}
//根树
type Trie struct {
root *Node
}
//创建一颗新树
func NewTrie() *Trie {
return &Trie{
root: &Node{
children: make(map[string]*Node),
},
}
}
//返回跟节点
func (t *Trie) Root() *Node {
return t.root
}
//添加节点
func (t *Trie) Add(lCode []string, name string) *Node {
node := t.root
for i := range lCode {
r := lCode[i]
if n, ok := node.children[r]; ok {
node = n
} else {
// 否则就创建这个节点
node = node.NewChild(r, name)
}
}
return node
}
//创建并返回一个新子节点的指针这里的key
func (n *Node) NewChild(key string, value string) *Node {
node := &Node{
value: value,
children: make(map[string]*Node),
}
n.children[key] = node
return node
}
// 返回一个子叶
func (n Node) Children() map[string]*Node {
return n.children
}