Tree: Huffman Decoding

Sort by

recency

|

549 Discussions

|

  • + 0 comments

    Python code:

    def decodeHuff(root, s):

    #Enter Your Code Here
    
    n = len(s)
    
    i = 0
    
    node = root
    
    while i < n:
    
        if s[i] == "0":
    
            node = node.left
    
            if node.left == None and node.right == None:
    
                print(node.data, end = "")
    
                node = root
    
        else:
    
            node = node.right
    
            if node.left == None and node.right == None:
                print(node.data, end = "")
                node = root
    
        i = i + 1
    
  • + 0 comments

    The C langauge case, there is no binary tree passed and input is decoded string. Is one suppose to generate codes, create coded string and then call a function to decode a generated codeed string? Right now, just reading string from standard input and printing it back passes all test cases :-)

  • + 0 comments

    This explanation clearly walks through how frequency-driven structure makes Huffman coding efficient, especially with the step-by-step tree construction example. The idea of prioritizing high-frequency elements is similar to how systems like pay per call life insurance leads focus on value concentration rather than uniform distribution.

  • + 0 comments

    Python Recursive approach

    def get_value(node: Node, code: str, s: str, i: int) -> tuple[str, int]:
        
        if node is None:
            return code, i
            
        # leaf node
        if node.data != '\x00':
            code += str(node.data)
            return code, i
            
        if i >= len(s):
            return code, i
            
        # not leaf node
        match s[i]:
            case '0':
                return get_value(node.left, code, s, i+1)
                
            case '1':
                return get_value(node.right, code, s, i+1)
                
            case _:
                raise ValueError('Invalid Input')
    
    def decodeHuff(root, s):
    
        i: int = 0
        out_str: str = ''
        while i < len(s):
            out_str, i = get_value(root, out_str, s, i)
    
        print(out_str)
    		
    		
    
  • + 1 comment
    void decode(String s, Node root) {        
        Node node = root;
    
        for (int i = 0; i < s.length(); i++) {
            node = s.charAt(i) == '0' ? node.left : node.right;
    
            if (node.left == null && node.right == null) {
                System.out.print(node.data);
                node = root;
            }
        }
    }