簡體   English   中英

Trie數據結構中的遍歷和打印鍵算法

[英]Traverse and print keys algorithm in Trie Data structure

我正在處理一個與Trie數據結構的實現有關的項目。 所需的方法之一是按dfs順序打印Trie的所有鍵。 每個節點將具有一個布爾變量,該變量指示其是否為終端節點,並且其引用存儲在其父節點的大小為10的數組中。 說分支的一部分是3456(3-> 4-> 5-> 6),5和6是終端節點,6是分支的最后一個節點->也就是說,在打印鍵時,我只需要為該分支打印345和3456。 但問題是我不確定如何使用遞歸執行此操作...有任何想法嗎?

順便說一下,不需要將這些關鍵數字作為變量存儲在每個節點中,只需通過數組中的相應索引對其進行引用即可(例如:3表示一個節點存儲在子節點中[3])

嘗試這樣的事情:

private Node Find(Node x, String key, int d)
{ // Return value associated with key in the subtrie rooted at x.
    if (x == null)
        return null;

    if (d == key.Length)
    {
        return x;
    }

    char c = key[d]; // Use dth key char to identify subtrie.

    return Find(x.Children[c], key, d + 1);
}

public IEnumerable<String> GetAllKeys()
{
    Queue<String> q = new Queue<String>();
    Collect(Find(Root, "", 0), "", q);
    return q;
}

private void Collect(Node x, String pre, Queue<String> q)
{
    if (x == null) return;
    if (x.NullNode) q.Enqueue(pre);
    for (int c = 0; c < 256; c++)
        Collect(x.Children[c], pre + ((char)c), q);
}

但是,您可能需要對實現進行一些調整。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM