Tree: Huffman Decoding

  • + 0 comments

    Java 8 Solution:-

    class Decoding {
        public void decode(String s, Node root) {
            StringBuilder decoded = new StringBuilder();
            Node currentNode = root;
            for (int i = 0; i < s.length(); i++) {
                if (s.charAt(i) == '0') {
                    currentNode = currentNode.left;
                } else {
                    currentNode = currentNode.right;
                }
                if (currentNode instanceof HuffmanLeaf) {
                    decoded.append(currentNode.data);
                    currentNode = root;  
                }
            }
            System.out.println(decoded.toString());
        }
    }