我的想法是将字符转换为二进制。例如,“ 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)){”
最佳答案
ab = new EDBinaryTree<Character>(null, a, hijoder);
我猜这将创建一个具有
null
数据的节点从
data == null
开始 if(ab.root.data.equals(car))
将失败