實(shí)現(xiàn)一個(gè)簡(jiǎn)單的tire樹(shù)

Tire樹(shù)(也稱為Trie樹(shù))是一種樹(shù)形數(shù)據(jù)結(jié)構(gòu),用于存儲(chǔ)動(dòng)態(tài)集或關(guān)聯(lián)數(shù)組,其中鍵是序列(通常為字符串)。Tire樹(shù)的節(jié)點(diǎn)存儲(chǔ)與鍵相關(guān)聯(lián)的值以及存儲(chǔ)鍵本身的地方。節(jié)點(diǎn)在樹(shù)中的位置定義了與之相關(guān)聯(lián)的鍵。

tire樹(shù)在日常開(kāi)發(fā)中應(yīng)用也是比較廣泛的

Tire樹(shù)可以用于實(shí)現(xiàn)自動(dòng)補(bǔ)全搜索功能。例如,當(dāng)用戶在搜索框中輸入一個(gè)字符串時(shí),可以使用Tire樹(shù)來(lái)快速查找所有以該字符串為前綴的關(guān)鍵字。這樣,用戶就可以在輸入過(guò)程中看到建議的關(guān)鍵字,并選擇其中之一進(jìn)行搜索。

這是一個(gè)使用Go實(shí)現(xiàn)Tire樹(shù)的示例:

package main

import "fmt"

const alphabetSize = 26

// TrieNode表示Trie樹(shù)中的一個(gè)節(jié)點(diǎn)。
type TrieNode struct {
    children [alphabetSize]*TrieNode
    isEnd    bool
}

// Trie是一個(gè)Trie樹(shù)。
type Trie struct {
    root *TrieNode
}

// Insert將鍵插入Trie中。
func (t *Trie) Insert(key string) {
    node := t.root
    for i := 0; i < len(key); i++ {
        index := key[i] - 'a'
        if node.children[index] == nil {
            node.children[index] = &TrieNode{}
        }
        node = node.children[index]
    }
    node.isEnd = true
}

// Search在Trie中搜索鍵,如果存在則返回true,否則返回false。
func (t *Trie) Search(key string) bool {
    node := t.root
    for i := 0; i < len(key); i++ {
        index := key[i] - 'a'
        if node.children[index] == nil {
            return false
        }
        node = node.children[index]
    }
    return node.isEnd
}

func (t *Trie) Print() {
    printUtil(t.root, "", 0)
}

func printUtil(node *TrieNode, str string, level int) {
    if node == nil {
        return
    }
    if node.isEnd {
        fmt.Println(str)
    }
    if isLeafNode(node) {
        return
    }
    for i := 0; i < alphabetSize; i++ {
        c := i + 'a'
        printUtil(node.children[i], str+string(c), level+1)
    }
}

func isLeafNode(node *TrieNode) bool {
    for i := 0; i < alphabetSize; i++ {
        if node.children[i] != nil {
            return false
        }
    }
    return true
}

func main() {
    trie := Trie{root: &TrieNode{}}
    trie.Insert("hello")
    trie.Insert("world")
    fmt.Println(trie.Search("hello"))
    fmt.Println(trie.Search("world"))
    fmt.Println(trie.Search("hell"))
    fmt.Println(trie.Search("worl"))
    trie.Print()
}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容