0

我的想法是将字符转换为二进制。例如,“f”将是“100”。为了尝试这个例子,我在下面的代码中创建了扩展二叉树:

二叉树

package ej2;

public class PrincipalCod {

/**
 * @param args
 */
public static int cont = 0;

public static String visitNode(EDBinaryTree<Character> ab, char car, String decode) {

    cont++;
    System.out.println("Cont: "+cont);

    if(ab.getLeftSubTree() != null) {
        visitNode(ab.getLeftSubTree(), car, decode+"0");
    }
    if(ab.getRightSubTree() != null) {
        visitNode(ab.getRightSubTree(), car, decode+"1");
    }
    if(ab.getLeftSubTree() == null && ab.getRightSubTree() == null) {
        //OMG! leaf!
        if(ab.root.data.equals(car)){
            return decode;
        }else{
            decode="";
        }
    }
    return null;
}

private static String codificar(EDBinaryTree<Character> ab, char car){
    return visitNode(ab, car, "");
}

public static void main(String[] args) {
    char caracter = 'f';
    EDBinaryTree<Character> ab = new EDBinaryTree<Character>();
    //i create leaf nodes
    EDBinaryTree<Character> a = new EDBinaryTree<Character>('a');
    EDBinaryTree<Character> f = new EDBinaryTree<Character>('f');
    EDBinaryTree<Character> b = new EDBinaryTree<Character>('b');
    EDBinaryTree<Character> c = new EDBinaryTree<Character>('c');

    EDBinaryTree<Character> sonrightleft = new EDBinaryTree<Character>(null, f, b);
    EDBinaryTree<Character> sonright = new EDBinaryTree<Character>(null, hijoderizq, c);
    ab = new EDBinaryTree<Character>(null, a, hijoder);
    System.out.println("-----Tree used--------");
    ab.displayTree();
    System.out.println("----------------------------");
    String cod = codificar(ab, caracter);
    System.out.println("Solution: "+cod);
}

}

任何想法?

在 Eclipse 中测试它,它说:

Exception in thread "main" java.lang.NullPointerException
at ej2.PrincipalCod.visitNode(PrincipalCod.java:23)
at ej2.PrincipalCod.visitNode(PrincipalCod.java:16)
at ej2.PrincipalCod.visitNode(PrincipalCod.java:16)
at ej2.PrincipalCod.codificar(PrincipalCod.java:33)
at ej2.PrincipalCod.main(PrincipalCod.java:50)

它在行中崩溃:“if(ab.root.data.equals(car)){”

4

1 回答 1

1
ab = new EDBinaryTree<Character>(null, a, hijoder);

我猜这会创建一个带有null数据的节点

既然data == null,那么

    if(ab.root.data.equals(car))

将失败

于 2013-06-11T02:05:01.647 回答