Now with your compress code--Your code just says: run down the left side until your hit a leaf--then you do nothing for that clasue, but if it's not a leaf, then run down the left side, until you hit a null, then go right. So you have a left branch that has 5 nodes and then there isn't a right. So as you ask, it looks down the left nodes not finding the target, so continuing down the left side as asked.
Once you start down that left side in your code--you either find what you are looking for, or you end when you hit the end of the branch, there isn't anything to make it branch right as long as there is a left. If you are looking to return from your recursive call and go right, then you have not developed a proper halting condition, nor have you developed the proper logic to get feedback into your previous instance, to know to do anything other than return out leaving you with the skewed left result.
Draw a tree on paper and traverse the tree according to your algo--not what you think it does, but exactly what the code says to do, then take a few minutes and trace to get the answer. Once you can get the answer write that algo down, and implement it.
Recursion is simple and elegant, but wicked and devilish is you make any mistakes at all.
java do wrote:I try to compress just one character in huffman tree. If the data is the searched one, return. If not go traversing left or right. For example: I hope to get 1010 for a or 00001 for t (a and t is kind of symbol). But I get 11111. How can be the issue fixed?
Your StringBuilder result, is an object passed in from outside the scope of your recursive method, so even though, Java passes by value, the value that it passes is the reference not the object, so, "in effect", what you have implemented by using the object reference there is a pass by reference outcome. That means you have bypassed the statefulness of the recursive instance with respect to your result--when you change result, it will not go back to it's prior value if you return to a previous instance of compress.