📜  Trie的自底向上遍历

📅  最后修改于: 2021-04-17 12:14:32             🧑  作者: Mango

Trie是一种有效的信息检索数据结构。使用Trie,可以使搜索复杂度达到最佳极限(密钥长度)。
试了一下。任务是以自下而上的方式打印字符
向上遍历

它类似于树的后遍历
例子:

Input :
                                          root
                                         /    \    
                                         a     t     
                                         |     |     
                                         n     h     
                                         | \   |   
                                         s  y  e     
                                         |     |  \ 
                                         w     i   r
                                         |     |   |
                                         e     r   e
                                         |        
                                         r        
Output : r, e, w, s, y, n, a, r, i, e, r, e, h, t  

Input : 
                                           root
                                          /     \    
                                         c       t     
                                         |       |     
                                         a       h     
                                         | \     |     
                                         l  t    e     
                                         |       |  \ 
                                         l       i   r
                                         | \     |   |
                                         e  i    r   e
                                         |  |
                                         r  n
                                            |
                                            g 

Output : r, e, g, n, i, l, l, t, a, c, r, i, e, r, e, h, t

解释 :
在第一个示例中,根有两个部分。第一部分包含字符串:“答案”和“任何”。
第二部分使用字符串“ their”和“ there”。

  • 现在,我们首先离开子树,其中包含用字符“ n”分隔的字符串“ answer”和“ any”。现在,“ n”将字符“ s”,“ w”,“ e”,“ r”和“ y”的两部分分开。因此,以相反的顺序打印“ s”,“ w”,“ e”,“ r”,然后打印“ y”并向上打印“ n”(分隔字符串),然后向上打印“ a”。现在,左下子树以自下而上的方式打印“ r”,“ e”,“ w”,“ s”,“ y”,“ n”,“ a”。
  • 对根的另一个子树执行相同的操作,该子树包含用字符“ e”分隔的字符串“ their”和“ there”。

方法 :
这样做的想法是从trie的根节点开始遍历,每当我们找到NON-NULL子节点时,当我们得到“ NULL”时我们便递归地前进,我们简单地返回并打印当前节点的值,并且相同直到找到一个叶子节点(实际上是标记字符串的结尾)的节点。
下面是上述方法的实现:

CPP
// CPP program to traverse in bottom up manner
#include 
using namespace std;
#define CHILDREN 26
#define MAX 100
 
 
// Trie node
struct trie {
    trie* child[CHILDREN];
    // endOfWord is true if the node represents
    // end of a word
    bool endOfWord;
};
 
// Function will return the new node(initialized to NULLs)
trie* createNode()
{
    trie* temp = new trie();
    temp->endOfWord = false;
    for (int i = 0; i < CHILDREN; i++) {
        // Initialise all child to the null, initially
        temp->child[i] = NULL;
    }
     
    // Return newly created node
    return temp;
}
// Function will insert the string in a trie recursively
void insertRecursively(trie* itr, string str, int i)
{
    if (i < str.length()) {
        int index = str[i] - 'a';
        if (itr->child[index] == NULL) {
            // Assining a newly created node
            itr->child[index] = createNode();
        }
        // Recursive call for insertion
        // of a string in a trie
        insertRecursively(itr->child[index], str, i + 1);
    }
    else {
        // Make the endOfWord true which represents
        // the end of string
        itr->endOfWord = true;
    }
}
// Function call to insert a string
void insert(trie* itr, string str)
{
    // Function call with necessary arguments
    insertRecursively(itr, str, 0);
}
// Function to print traverse
// the tree in bottum to top manner
void printPattern(trie* itr)
{
    // Base condition
    if (itr == NULL)
        return;
 
    // Loop for printing t a value of character
    for (int i = 0; i < CHILDREN; i++) {
         
        // Recursive call for print pattern
        printPattern(itr->child[i]);
        if (itr->child[i] != NULL) {
            char ch = (i + 97);
            cout << ch << ", "; // Print character
        }
    }
}
 
// Driver code
int main()
{
    trie* root = createNode();
     
    // Function to insert a string
    insert(root, "thier");
    insert(root, "there");
    insert(root, "answer");
    insert(root, "any");
     
     
    // Function call for printing a pattern
    printPattern(root);
 
    return 0;
}


Python3
# Python3 program to traverse in bottom up manner
CHILDREN = 26
MAX = 100
 
# Trie node
class trie:
 
    def __init__(self):
        self.child = [None for i in range(CHILDREN)]
         
        # endOfWord is true if the node represents
        # end of a word
        self.endOfWord = False
 
# Function will return the new node(initialized to NULLs)
def createNode():
 
    temp = trie()
    return temp
 
# Function will insert the string in a trie recursively
def insertRecursively(itr, str, i):
 
    if (i < len(str)):
        index = ord(str[i]) - ord('a')
         
        if (itr.child[index] == None):
           
            # Assining a newly created node
            itr.child[index] = createNode()
         
        # Recursive call for insertion
        # of a string in a trie
        insertRecursively(itr.child[index], str, i + 1)
     
    else:
        # Make the endOfWord true which represents
        # the end of string
        itr.endOfWord = True
     
# Function call to insert a string
def insert(itr, str):
 
    # Function call with necessary arguments
    insertRecursively(itr, str, 0)
 
# Function to print traverse
# the tree in bottum to top manner
def printPattern(itr):
 
    # Base condition
    if(itr == None):
        return
 
    # Loop for printing t a value of character
    for i in range(CHILDREN):
 
        # Recursive call for print pattern
        printPattern(itr.child[i])
        if (itr.child[i] != None):
            ch = chr(i + 97)
             
            # Print character
            print(ch,end=', ')
             
# Driver code
if __name__=='__main__':
 
    root = createNode()
 
    # Function to insert a string
    insert(root, "thier")
    insert(root, "there")
    insert(root, "answer")
    insert(root, "any")
 
    # Function call for printing a pattern
    printPattern(root)
 
    # This code is countributed by rutvik_56


输出:

r, e, w, s, y, n, a, e, r, e, r, e, i, h, t,