...

/

Solution Review: Finding All Words Stored in Trie

Solution Review: Finding All Words Stored in Trie

Learn a detailed analysis of the different ways to solve the “Finding All Words Stored in Trie” challenge.

We'll cover the following...

Solution: Recursion #

Press + to interact
main.cs
Trie.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace chapter_7
{
class Program
{
static void getWords(TrieNode root, List<string> result, int level, ref string word)
{
//Leaf denotes end of a word
if (root.isEndWord)
{
//current word is stored till the 'level' in the word string
string temp = "";
for (int x = 0; x < level; x++)
{
temp += word[x];
}
result.Add(temp);
}
for (int i = 0; i < 26; i++)
{
if (root.children[i] != null)
{
if(level < word.Length)
{
StringBuilder sb = new StringBuilder(word);
sb[level] = (char)(i + 'a');
word = sb.ToString();
}
else
{
word += (char)(i + 'a');
}
getWords(root.children[i], result, level + 1, ref word);
}
}
}
static List<string> findWords(TrieNode root)
{
List<string> result = new List<string> () ;
string word = "";
getWords(root, result, 0,ref word);
return result;
}
static void Main(string[] args)
{
string [] keys = { "the", "a", "there", "answer", "any", "by", "bye", "their", "abc" };
Trie t = new Trie();
// Construct trie
for (int i = 0; i < 9; i++)
{
t.insertNode(keys[i]);
}
List<string> ans = findWords(t.getRoot());
for (int i = 0; i < ans.Count; i++)
{
Console.WriteLine( ans[i] );
}
return;
}
}
}

The findWords(root) function contains a ...