Tree: Huffman Decoding

  • + 1 comment

    Java 8 solution:

    void decode(String s, Node root) {
            StringBuilder decodedString = new StringBuilder();
            Node currentNode = root;
            
            char[] codeArray = s.toCharArray();
            
            for (char c : codeArray) {
                if (currentNode.left != null && c == '0') {
                    currentNode = currentNode.left;
                } else if (currentNode.right != null && c == '1') {
                    currentNode = currentNode.right;
                }
                
                if (currentNode.left == null && currentNode.right == null) {
                    decodedString.append(currentNode.data);
                    currentNode = root;
                }
            }
            
            System.out.println(decodedString.toString());
        }
    
    • + 0 comments

      Hi, I have somethig similar to your code, just without the verification if the left or right node exists because if it was coded on the string, the path should exists.

      	void decode(String s, Node root) {
              Node head = root;
              char[] chars = s.toCharArray();
              for(int i = 0; i < chars.length; i++){
                  if(chars[i]=='0'){
                      head = head.left;
                  } else{
                      head = head.right;
                  }
                  if(head.left == null && head.right == null){ 
                      System.out.print(head.data);
                      head=root;
                  }
              }
               
          }