Tree: Huffman Decoding

Sort by

recency

|

543 Discussions

|

  • + 0 comments

    This test code is broken for Javascript, The code was expecting that i should do encode and decode both. However question was for decoding the string and it should provide root node and encoded string. Just printing the input string passed it.

  • + 1 comment

    Java 8:

        private int printLeaf(int stepNum, String s, Node node) {
            if (Objects.nonNull(node.left) && s.charAt(stepNum) == '0')
                stepNum = printLeaf(stepNum + 1, s, node.left); 
            else if (Objects.nonNull(node.right) && s.charAt(stepNum) == '1')
                stepNum = printLeaf(stepNum + 1, s, node.right);
            
            System.out.print(node.data);
            return stepNum;
        }
    
    void decode(String s, Node root) {
            int cur = 0;
            while (cur < s.length()) cur = printLeaf(cur, s, root);
        }
    

    Not sure what am I missing, it prints all the correct valued in the output, but shows "Wrong answer".

  • + 0 comments

    C++ 14 solution:

    void decode_huff(node * root, string s) {
         if(root == NULL || s.empty() || s == ""){
            cout<<"";
            return;
        }
        
        auto temp = root;
        for(auto c : s){
            temp = c == '0' ? temp->left : temp->right;                
            
            if(temp && temp->data){
                cout<<temp->data;
                temp = root;
            }
        }    
    }
    
  • + 1 comment

    To save some headaches (at least in Python): The problem says intermediate nodes contain null. You'd expect that to be None, but it's a non-printable '\x00'

  • + 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);
        }