Tree: Huffman Decoding

Sort by

recency

|

9 Discussions

|

  • + 0 comments

    Java, O(n)

    void decode(String s, Node root) {
            StringBuilder decodedString = new StringBuilder();
            Node current = root;
            
            for (int i = 0; i < s.length(); i++) {
                char bit = s.charAt(i);
                if (bit == '0') {
                    current = current.left;
                } else {
                    current = current.right;
                }
                
                if (current instanceof HuffmanLeaf) {
                    HuffmanLeaf leaf = (HuffmanLeaf) current;
                    decodedString.append(leaf.data);
                    current = root;
                }
            }
            
            System.out.println(decodedString.toString());
        }
    
  • + 0 comments

    Javascript

    function processData(input) {
        //Enter your code here
        console.log(input);
    }
    
  • + 0 comments

    Python

    def decodeHuff(root, s):
        current = root
        for c in s: 
            current = current.left if c == '0' else current.right
            if current.data!='\0':
                print(current.data, end = '')
                current = root
    
  • + 0 comments

    def decodeHuff(root, s): #Enter Your Code Here

    code = ''
    start = 0 
    end = 0
    n = len(s)
    node = root
    #print(node.left.data)
    while end < n:
        # print(code)
        # print(end)
    
        if node.left or node.right:
            if s[end] == '0':
                node = node.left
            else:#=1
                node = node.right
            end+=1
        else:#stop letter
            # print('stop letter')
            code = code + node.data
            node = root
    code = code + node.data#Last potential letter excluded from loop
    print (code)
    
  • + 0 comments

    C++

    void decode_huff(node * root, string s) {
        
        node* curr=root;
        for(int i=0;i<s.length();i++)
        {
            if(s[i]=='0')
                curr=curr->left;
            else
                curr=curr->right;
        
            if(curr->left==NULL && curr->right==NULL)
            {
                cout<<curr->data;
                curr=root;
            }
        }
    }