Help with Huffman Binary Tree JAVA coding with strings

2
public String codificar(String text) {
    String res="";
    if (!text.isEmpty()){
        for (int i = 0; i<text.length(); i++){
            res+=busquedaDelCaracter(text.charAt(i), this.huffmanTree, this.huffmanTree.root(), res);
        }
    }
    return res;
}


public String busquedaDelCaracter(Character ch, BinaryTree<Character> tree, Position<Character> pos, String path) {
    if(tree.isExternal(pos)){
        return path+busquedaDelCaracter(ch,tree,pos,path)==null?"":busquedaDelCaracter(ch,tree,pos,path);
    }
    if(tree.hasLeft(pos)){
        busquedaDelCaracter(ch,tree,tree.left(pos),"0"+path);
    }
    return path+busquedaDelCaracter(ch,tree,pos,path) == null?"":busquedaDelCaracter(ch,tree,tree.right(pos),"1"+path);     
}

I put you in situation:

This is an exercise based on Huffman coding, only work with simple data structures.

Example of Huffman coding:

            .
           / \
           a  .
               \
                .
               / \
              c  d

codificar("acd") ---> "0110111"
A la derecha = 1
A la izquierda = 0

Currently I have the code that I have shown you to code and the recursive method busquedaDelCaracter . I do not know where the fault may be, could you guide me a bit?

Note, if you can not find a character, it's null but when you return it you can not concatenate nulls.

Code already done and with 0 problems:

public String decode(String textocifrado) {

    Position <Character> cursor = this.huffmanTree.root();
    String decodeText="";

    for(int i=0; i<textocifrado.length(); i++){
        if(textocifrado.charAt(i) == '1'){
            cursor = this.huffmanTree.right(cursor);
        }
        if(textocifrado.charAt(i) == '0'){
            cursor = this.huffmanTree.left(cursor);
        }
        if(this.huffmanTree.isExternal(cursor)){
            decodeText+=cursor.element();
            cursor=this.huffmanTree.root();
        }           
    }   
    return decodeText;
}

And the constructor only works with a char[]paths with a LinkedBinaryTree called HuffmanTree and what it does is form the tree (you do not need to call the constructor) in the exercise I'm asking for help.

    
asked by Miguel Redondo 05.12.2016 в 05:18
source

0 answers