0

I need to fill a binary tree using only class Node with recursion. However when I try to use left and right children I get a NullPointerException. How should I fix it?

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);
}

}

Igor K
  • 67
  • 1
  • 5
  • Could you please add the calls to addValue you are doing and the stacktrace to help us determine where the issue is? Apparently you never create new Nodes (you never call the constructor) so both right and left will always be null. – Guido Apr 15 '18 at 09:46
  • where do you initialize `left` and `right` ? – c0der Apr 15 '18 at 09:55
  • I have added it. – Igor K Apr 15 '18 at 12:33
  • i think that I initialize them with help of this public Node right; public Node left; – Igor K Apr 15 '18 at 12:34

0 Answers0