Search code examples
javatraversalhuffman-code

Assigning bits for huffman encoding


I'm having trouble finding a way to assign the 0's and 1's for the letters. I fixed my priority queue so that it will make all the nodes into a tree with the highest priority first. I am out of ideas on how to assign each letter its value. I was thinking of using an inorder traversal but am stuck on how that code will look when adding the bits to the letters. All help is greatly appreciated! My node class is below:

private class Node{
    Node right;
    Node left;
    Node parent;
    char letter;
    int value;
    String binaryValue = "";
    private Node(char c, int in, Node parent, Node left, Node right){
        letter = c;
        value = in;
        this.left = left;
        this.right = right;
        this.parent = parent;
    }
    @SuppressWarnings("unused")
    private void setRight(Node right){
        this.right = right;
    }
    @SuppressWarnings("unused")
    private void setLeft(Node left){
        this.left = left;
    }
    private void setParent(Node parent){
        this.parent = parent;
    }
    private Node getParent(){
        return parent;
    }
    @SuppressWarnings("unused")
    private void setWeight(int weight){
        this.value += weight;
    }
    private void setBinary(String binary){
        binaryValue = binary;
    }
    private String getBinary(){
        return binaryValue;
    }
}

Solution

  • Not sure exactly what your asking but this might be one solution to your problem

    char letter = c;
      byte[] bytes = letter.getBytes();
      StringBuilder binary = new StringBuilder();
      for (byte b : bytes)
      {
         int val = b;
         for (int i = 0; i < 8; i++)
         {
            binary.append((val & 128) == 0 ? 0 : 1);
            val <<= 1;
         }
         binary.append(' ');
      }
      System.out.println(binary);