APCS Free Response 2002 AB4 Java Version ANSWERS

CodeTree.java source.

public class CodeTree
{
    /**
     * Construct a codetree.
     */
    
    public CodeTree()
    {
	myRoot = new TreeNode("",
                     new TreeNode("",
		         new TreeNode("s",null,null),
		         new TreeNode("",
				      new TreeNode("u",null,null),
				      new TreeNode("y",null,null))),
		     new TreeNode("",
		         new TreeNode("n",null,null),
		         new TreeNode("i",null,null)));
					   
    }

    /**
     * Returns a decoded word for code.
     * @precondition code valid string of 0's and 1's
     * @return the decoded word for code
     */
    
    public String bitsToWord(String code)
    {
	TreeNode current = myRoot;
	String result = "";

	for(int k=0; k < code.length(); k++) {
	    if (code.substring(k,k+1).equals("0")) {
		current = current.getLeft();
	    }
	    else {
		current = current.getRight();
	    }
	    if (current.getLeft() == null &&
		current.getRight() == null) {  // it's a leaf?
		result += current.getValue();
		current = myRoot;
	    }
	}
	return result;
    }

    /**
     * Returns the code for word
     * @precondition each character of word is in a leaf of codetree
     * @return the code for word
     */

    public String wordToBits(String word)
    {
	String result = "";
	for(int k=0; k < word.length(); k++) {
	    result += wordToBitsHelper(word.substring(k,k+1),myRoot,"");
	}
	return result;
    }

    /**
     * Returns the code for s in codetree, returns "" if s not in tree
     * @precondition pathSoFar is path of 0's and 1's from myRoot to t
     * @return the path from myRoot to leaf containing s ,"" if no path
     */

    private String wordToBitsHelper(String s, TreeNode t,
				    String pathSoFar)
    {
	if (t.getLeft() == null && t.getRight() == null) {  // leaf?
	    if (t.getValue().equals(s)) {
		return pathSoFar;
	    }
	    else {
		return "";
	    }
	}
	String result = wordToBitsHelper(s,t.getLeft(),
					 pathSoFar+"0");
	if (result.length() > 0) {
	    return result;
	}
	return wordToBitsHelper(s,t.getRight(),pathSoFar+"1");

    }

    private TreeNode myRoot;

    public static void main(String[] args)
    {
	CodeTree ct = new CodeTree();
	System.out.println(ct.bitsToWord("1110"));
	System.out.println(ct.bitsToWord("000101010011"));
	System.out.println();
	System.out.println(ct.wordToBits("in"));
	System.out.println(ct.wordToBits("sunny"));
    }
}


Owen L. Astrachan
Last modified: Thu Jul 11 13:59:23 EDT 2002