Tree: Huffman Decoding

  • + 0 comments

    Java 8 solution, with recursion instead of loop:

    private int index = 0;
        void decode(String s, Node root) {
            char[] chars = s.toCharArray();
            StringBuilder sb = new StringBuilder();
            while (index < chars.length) {
                Character ss = navigateAndGet(chars, root);
                if (ss != null) {
                    sb.append(ss);
                }
            }
            System.out.print(sb);
        }
    
        private Character navigateAndGet(char[] chars, Node node) {
            if (node.left == null && node.right == null) {
                return node.data;
            }
            if (index == chars.length) {
                return null;
            }
            Node nextNode;
            if (chars[index] == '0') {
                nextNode = node.left;
            } else {
                nextNode = node.right;
            }
            index++;
            return navigateAndGet(chars, nextNode);
        }