Created
April 15, 2013 06:42
-
-
Save chintanparikh/5386159 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static Map<Character, EncodedString> buildEncodingMap(Node tree) { | |
return buildEncodingMap(tree, new EncodedString()); | |
} | |
public static Map<Character, EncodedString> buildEncodingMap(Node node, EncodedString string) | |
{ | |
if (node.character != 0) | |
{ | |
// The node has a character, frequency mapping | |
HashMap<Character, EncodedString> map = new HashMap<Character, EncodedString>(); | |
map.put(node.character, string); | |
return map; | |
} | |
else | |
{ | |
// Traverse the tree, and recursively build the map | |
return traverseAndBuild(node, string); | |
} | |
} | |
protected static Map<Character, EncodedString> traverseAndBuild(Node node, EncodedString string) | |
{ | |
Iterator iter = string.iterator(); | |
EncodedString left = new EncodedString(); | |
EncodedString right = new EncodedString(); | |
while(iter.hasNext()) | |
{ | |
Byte next = (Byte) iter.next(); | |
if (next == EncodedString.ONE) | |
{ | |
left.one(); | |
} | |
else if (next == EncodedString.ZERO) | |
{ | |
left.zero(); | |
} | |
} | |
left.zero(); | |
iter = string.iterator(); | |
while(iter.hasNext()) | |
{ | |
Byte next = (Byte) iter.next(); | |
if (next == EncodedString.ONE) | |
{ | |
right.one(); | |
} | |
else if (next == EncodedString.ZERO) | |
{ | |
right.zero(); | |
} | |
} | |
right.one(); | |
return mergeMaps(buildEncodingMap(node.left, left), buildEncodingMap(node.right, right)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment