我在不使用频率的情况下构建huffmanTree时遇到问题,用户将直接输入字符和二进制数给huffmanTree。根据用户输入,如果二进制的第一个输入是0,它应该向左,如果它是1,它应该向右。当插入第二个二进制代码时,程序应检查该位置是否为叶子。如果是叶子,请插入。如果没有返回该地点的消息。
我想出了一个回复错误的想法。
线程“main”java.lang.NullPointerException中的异常 在ideas.ideas.insert(ideas.java:70)
import java.util.LinkedList;
import java.util.Scanner;
class Node {
char data;
int idata;
boolean isCreated = false;
Node leftChild, rightChild;
public Node(char data) {
this.data = data;
leftChild = new Node();
rightChild = new Node();
}
public Node() {
}
}
public class ideas{
Node root = new Node();
public ideas(){
root.isCreated = true;
}
void insert(char data, String bin) {
Node newNode = new Node();
newNode.isCreated=true;
if (!root.isCreated) {
System.out.println("It never enters here, since the root is always empty and is created with the constructor ");
root = newNode;
root.isCreated = true;
} else {
System.out.println("");
Node current = root;
Node parent = current;
int i = 0;
while (i < bin.length()) {
parent = current;
if (bin.charAt(i) == '0') {
System.out.println("Parent leftChild is : "+newNode.isCreated);
current = current.leftChild;
// System.out.println("Current left child is : "+current.isCreated);
if (current.isCreated == false) {
parent.leftChild = newNode;
current.isCreated = true;
// current.idata = 0;
//return;
i++;
}
} else {
current = current.rightChild;
if (current.isCreated == false) {
parent.rightChild = newNode;
current.isCreated = true;
//current.idata = 1;
//return;
i++;
}
}
}
current.data = data;
System.out.println("the data is "+current.data);
}
}
void preOrder(Node current) {
if (current.isCreated == false) {
System.out.println(current.data);
preOrder(current.leftChild);
preOrder(current.rightChild);
}
}
public static void main(String[] args) {
System.out.println("Enter a character");
System.out.println("Enter its binary code");
ideas t = new ideas();
t.insert('e', "10101");
// t.insert('a', "00101");
t.preOrder(t.root);
}
}