gpt4 book ai didi

java - 使用 BinaryTree 将字符编码为二进制

转载 作者:行者123 更新时间:2023-12-01 14:27:59 26 4
gpt4 key购买 nike

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

BinaryTree

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)){”

最佳答案

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

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

由于data == null,那么

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

会失败

关于java - 使用 BinaryTree 将字符编码为二进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17035432/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com