본문 바로가기

알고리즘/해커랭크

[해커랭크] Tree: Huffman Decoding [JAVA]

문제링크 : www.hackerrank.com/challenges/tree-huffman-decoding/problem

 

Tree: Huffman Decoding | HackerRank

Given a Huffman tree and an encoded binary string, you have to print the original string.

www.hackerrank.com

문제 설명에 나온 허프만 인코딩의 특징은 리프 노드에 데이터가 담겨있다는 것이다.

문자열 s를 0번 인덱스부터 문자를 확인하며 명령어로 생각한다. 0일땐 왼쪽 1일땐 오른쪽으로 트리를 탐색하며

리프노드이면 출력하는 것을 반복한다. 

    public static void decode2(String s, Node root, int idx){
        if(idx >= s.length()) return;
         Node ROOT = root;
        while(root.left!=null && root.right!=null){
            if(s.charAt(idx)=='0') root= root.left;
            else root = root.right;
            idx++;
        }
        System.out.print(root.data);
        decode2(s,ROOT,idx);
    }

    void decode(String s, Node root) {
       decode2(s,root,0);
        
    }