private static void insert(Node root, int symbol, int code, byte length) { // traverse tree using the most significant bytes of code Node current = root; while (length > 8) { if (current.isTerminal()) { throw new IllegalStateException("invalid Huffman code: prefix not unique"); } length -= 8; int i = (code >>> length) & 0xFF; if (current.children[i] == null) { current.children[i] = new Node(); } current = current.children[i]; } Node terminal = new Node(symbol, length); int shift = 8 - length; int start = (code << shift) & 0xFF; int end = 1 << shift; for (int i = start; i < start + end; i++) { current.children[i] = terminal; } } }
private static void insert(Node root, int symbol, int code, byte length) { // traverse tree using the most significant bytes of code Node current = root; while (length > 8) { if (current.isTerminal()) { throw new IllegalStateException("invalid Huffman code: prefix not unique"); } length -= 8; int i = (code >>> length) & 0xFF; if (current.children[i] == null) { current.children[i] = new Node(); } current = current.children[i]; } Node terminal = new Node(symbol, length); int shift = 8 - length; int start = (code << shift) & 0xFF; int end = 1 << shift; for (int i = start; i < start + end; i++) { current.children[i] = terminal; } } }
private static Node buildTree(int[] codes, byte[] lengths) { Node root = new Node(); for (int i = 0; i < codes.length; i++) { insert(root, i, codes[i], lengths[i]); } return root; }
private static Node buildTree(int[] codes, byte[] lengths) { Node root = new Node(); for (int i = 0; i < codes.length; i++) { insert(root, i, codes[i], lengths[i]); } return root; }