u
This commit is contained in:
@@ -0,0 +1,90 @@
|
||||
package ds
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestTrieInsertSearch(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
words := []string{"apple", "app", "april", "banana"}
|
||||
for _, w := range words {
|
||||
tr.Insert(w)
|
||||
}
|
||||
for _, w := range words {
|
||||
if !tr.Search(w) {
|
||||
t.Fatalf("Search(%q) 应为 true", w)
|
||||
}
|
||||
}
|
||||
if tr.Search("appl") {
|
||||
t.Fatal("Search(\"appl\") 应为 false")
|
||||
}
|
||||
if tr.Search("apples") {
|
||||
t.Fatal("Search(\"apples\") 应为 false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrieStartsWith(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
for _, w := range []string{"apple", "app", "april"} {
|
||||
tr.Insert(w)
|
||||
}
|
||||
if !tr.StartsWith("app") {
|
||||
t.Fatal("StartsWith(\"app\") 应为 true")
|
||||
}
|
||||
if !tr.StartsWith("ap") {
|
||||
t.Fatal("StartsWith(\"ap\") 应为 true")
|
||||
}
|
||||
if tr.StartsWith("b") {
|
||||
t.Fatal("StartsWith(\"b\") 应为 false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrieDelete(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
tr.Insert("apple")
|
||||
tr.Insert("app")
|
||||
// 删 apple,app 应保留(共享前缀节点不能被回收)
|
||||
if !tr.Delete("apple") {
|
||||
t.Fatal("Delete(\"apple\") 应成功")
|
||||
}
|
||||
if tr.Search("apple") {
|
||||
t.Fatal("Delete 后 Search(\"apple\") 应为 false")
|
||||
}
|
||||
if !tr.Search("app") {
|
||||
t.Fatal("Search(\"app\") 仍应为 true (共享前缀)")
|
||||
}
|
||||
if !tr.StartsWith("app") {
|
||||
t.Fatal("StartsWith(\"app\") 仍应为 true")
|
||||
}
|
||||
|
||||
// 删不存在的单词
|
||||
if tr.Delete("xyz") {
|
||||
t.Fatal("Delete(\"xyz\") 应返回 false")
|
||||
}
|
||||
|
||||
// 删最后一个单词,根的对应子树应被完全回收
|
||||
tr.Delete("app")
|
||||
if tr.Search("app") {
|
||||
t.Fatal("Delete(\"app\") 后应搜不到")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrieDeleteNonWordPrefix(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
tr.Insert("apple")
|
||||
// "appl" 是前缀但不是完整单词,Delete 应返回 false
|
||||
if tr.Delete("appl") {
|
||||
t.Fatal("Delete(\"appl\") 非完整单词,应返回 false")
|
||||
}
|
||||
if !tr.Search("apple") {
|
||||
t.Fatal("apple 不应受影响")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrieEmpty(t *testing.T) {
|
||||
tr := NewTrie()
|
||||
if tr.Search("anything") {
|
||||
t.Fatal("空 Trie Search 应为 false")
|
||||
}
|
||||
if tr.StartsWith("a") {
|
||||
t.Fatal("空 Trie StartsWith 应为 false")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user