Tree: Huffman Decoding

  • + 0 comments
    void decode(String s, Node root) {
        StringBuilder res = new StringBuilder("");
        Node move = root;
        for(int i = 0; i < s.length(); i++ ) {
            if(Objects.equals(s.charAt(i), '0')){
    
                move = move.left;
    
                if(move != null && move.left == null && move.right == null ) {
                    res.append(move.data);
                    move = root;
                }
    
            } else if(Objects.equals(s.charAt(i), '1')){
    
                move = move.right;
    
                if(move != null && move.left == null && move.right == null ) {
                    res.append(move.data);
                    move = root;
                }
    
            } 
        }
    
       System.out.println(res.toString());
    }