我需要仅使用带有递归的类Node
来填充二叉树。但是,当我尝试使用左右儿童时,我得到NullPointerException
。我该如何解决?
public class Node {
private Integer key;
public Node right;
public Node left;
public void addValue(Integer value) {
if (key == null) {
key = value;
right = null;
left = null;
} else {
if (key > value) {
left.addValue(value);
left.right = null;
left.left = null;
} else {
right.addValue(value);
right.right = null;
right.left = null;
}
}
}
}
public class Main {
public static void main(String[] args) {
Node node = new Node();
node.addValue(5);
node.addValue(4);
node.addValue(3);
node.addValue(2);
node.addValue(1);
}
}