I have several lists:
A = [\"a0\", \"a1\"] // the number of lists varies
B = [\"b0\", \"b1\", \"b2\"] // such as the number of elements in a list.
C = [\"c
Something that I came up with working on printing the words in a TrieTree that can be easily adaptable to other kinds of trees or different needs:
public void rootToLeaves() {
HashMap hashMap = new HashMap();
for(TrieNode trieNode : root.getChildren())
rootToLeaves(trieNode, hashMap, 0);
}
private void rootToLeaves( TrieNode trieNode, HashMap hashMap, int heightIndex ) {
hashMap.put(heightIndex, trieNode);
if( trieNode.isLeaf() )
printValues(hashMap, heightIndex);
else
for( TrieNode childNode : trieNode.getChildren() )
rootToLeaves( childNode, hashMap, heightIndex + 1 );
}
private void printValues(HashMap hashMap, int heightIndex) {
for(int index = 0; index <= heightIndex; index++)
System.out.print(hashMap.get(index).getValue());
System.out.println();
}
This solution does a nice job in terms of memory management (It uses a single HashMap
whose size will never exceed the height of the tree) and it offers a lot of flexibility (Just replace printValues with whatever you need).
NOTE: Knowing the height of the tree in advance will let you use a simple Array
instead of a Map
.