-1

Here is my function, i seed it with the root node of my tree and a character to be found inside the tree. It successfully returns me the alphabet to be searched but it does not give me the path to the element. Im a bit stuck any help would be appriciated

public Node traversingTree(Node root,String charToFind){

    Node tempRoot = root;

    if (root != null){

        if (charToFind.equals(root.getAlphabet()))
        {
            //Another Point of consideration
            System.out.print(root.getAlphabet());
            System.out.println(": "+pathCodes);
            pathCodes.clear();
            return root;
        }
        Node result;

        if ((result = traversingTree(root.leftChild, charToFind)) != null){

            pathCodes.add("0");
            return result;

        }else
            pathCodes.add("1");
            return traversingTree(root.rightChild, charToFind); 
        }

        }
    pathCodes.clear();

     return null;

}

1 Answers1

1

You don't say exactly what you do get, but looking at your code, your right-hand recursion is adding the '1' before continuing down to look for the appropriate node. However you clear the code at the leaf node, which will occur after all the '1's have been added. So I'd expect your code to only contain '0's, as the '0's are appended after recursing.

Also I suspect that as you are adding the chars on the way back up the tree, the codes will be back to front.

While rethinking your recursion, I would recommend not using the huffman tree like this anyway. Searching for the codes is quite inefficient - I would suggest traversing the tree once, building a table of alphabet+code, and then simply indexing into that.

Preferably, use the tree only to calculate the code lengths, and generate the codes using a canonical encoding.

JasonD
  • 16,464
  • 2
  • 29
  • 44