/** * Same as above function, but using StringBuilder instead of int. This is only for readability * purpose. <br> * This is for traversing the tree and assigning the huffman code when leaf node is encountered * * @param rootNode Root node of the tree * @param code Empty stringBuilder, which */ static void huffManEncoding(CharFreq rootNode, StringBuilder code) { if (!rootNode.isLeafNode()) { // While going left append 0 code.append(0); huffManEncoding(rootNode.left, code); // while going right, append 1 code.append(1); huffManEncoding(rootNode.right, code); } else { rootNode.huffMan = Integer.parseInt(code.toString()); } // remove the last character while going back if (code.length() > 0) code.deleteCharAt(code.length() - 1); }
/** * @param rootNode * @param code Starting with 0 * @return It is used for just calculating the huffrecursion value further. It's is not returning * any final value */ static int huffManEncoding(CharFreq rootNode, int code) { if (!rootNode.isLeafNode()) { // While going left left shift one bit, so that 0 will be appended // at last code = code << 1; code = huffManEncoding(rootNode.left, code); // while going right, left shift 1 bit and Or with 1, so that 1 will // be appended at last code = (code << 1) | 1; code = huffManEncoding(rootNode.right, code); } else { rootNode.huffMan = code; } // While going back right shift by one bit, to discard it return code >> 1; }