...

/

Solution Review: List Sort Using Tries

Solution Review: List Sort Using Tries

Learn a detailed analysis of the different ways to solve the “List Sort Using Tries” challenge.

We'll cover the following...

Solution: Pre-order traversal

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> sortArray(string [] arr, int arr_length)
{
List<string> result = new List<string>();
//Creating Trie and Inserting words from array
Trie trie = new Trie();
for (int x = 0; x < arr_length; x++)
trie.insertNode(arr[x]);
string str = string.Empty;
getWords(trie.getRoot(), result, 0, ref str);
return result;
}
static void Main(string[] args)
{
string []keys = { "the", "a", "there", "answer", "any", "by", "bye", "their", "abc" };
List<string> ans = sortArray(keys, 9);
for (int i = 0; i < ans.Count; i++)
{
Console.WriteLine(ans[i]);
}
return;
}
}
}

This exercise is similar to Challenge 2, except you have to create the trie ...