-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortElementInTrie.java
More file actions
73 lines (66 loc) · 2.07 KB
/
SortElementInTrie.java
File metadata and controls
73 lines (66 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package datastructure.trie;
import java.util.ArrayList;
import java.util.Arrays;
/**
* The type Sort element in trie.
*/
public class SortElementInTrie {
/**
* Gets words.
*
* @param root the root
* @param result the result
* @param level the level
* @param str the str
*/
//Recursive Function to generate all words in alphabetic order
public static void getWords(TrieNode root, ArrayList<String> result, int level, char[] str) {
//Leaf denotes end of a word
if (root.isEndWord()) {
//current word is stored till the 'level' in the character array
String temp = "";
for (int x = 0; x < level; x++) {
temp += Character.toString(str[x]);
}
result.add(temp);
}
for (int i = 0; i < 26; i++) {
if (root.getChildren()[i] != null) {
//Non-null child, so add that index to the character array
str[level] = (char) (i + 'a');
getWords(root.getChildren()[i], result, level + 1, str);
}
}
}
/**
* Sort array array list.
*
* @param arr the arr
* @return the array list
*/
public static ArrayList<String> sortArray(String[] arr) {
ArrayList<String> result = new ArrayList<>();
Trie trie = new Trie();
for (int i = 0; i < arr.length; i++) {
trie.insert(arr[i]);
}
char[] charArray = new char[20];
getWords(trie.getRoot(), result, 0, charArray);
return result;
}
/**
* Main.
*
* @param args the args
*/
public static void main(String args[]) {
// Input keys (use only 'a' through 'z' and lower case)
String keys[] = {"the", "a", "there", "answer", "any",
"by", "bye", "their", "abc","ZETA","A"};
System.out.println("Keys: " + Arrays.toString(keys));
ArrayList<String> list = sortArray(keys);
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
}