0

Here is my code Can someone tell me why I always get null pointer exception in the line "current.children.add(tempnode);"

I have already revised it several times by getting the similar answer from here,but it can not work eventually.

class Node{
    int val;
    List<Node> children;
    
    public Node() {}

    public Node(int _val) {
        val = _val;
        }

    public Node(int _val, List<Node> _children) {
        val = _val;
        children = _children;
        }
}

public static Node BuildTree(Integer[] nodes) {
        //Integer[] nodes=new Integer[] {1,null,3,2,4,null,5,6}
        if(nodes==null||nodes.length==0)return null;
        Queue<Node> treenodequeue=new LinkedList<>();
        Queue<Integer> integerqueue=new LinkedList<>();
        Node root=new Node(nodes[0]);
        for(int i=1;i<nodes.length;i++)integerqueue.offer(nodes[i]);
        while(!integerqueue.isEmpty()){
            Node current=treenodequeue.poll();
            integerqueue.remove(null);
            while(integerqueue.peek()!=null) {
                Integer tempvalue=integerqueue.poll();
                Node tempnode=new Node(tempvalue);
/******************************************************************/
                current.children.add(tempnode);
/******************************************************************/
                treenodequeue.offer(tempnode);
            }
        }
        return root;
    }
ErnestL1n
  • 3
  • 3
  • Whenever you call the `Node(int)` constructor, the `children`-list is never initialized and thus `null`. Either call the other constructor `Node(int, List)` or by default simply initialize the list in the `Node(int)` constructor – Lino Jul 01 '20 at 11:59
  • public Node(int _val) { val = _val; this.children=new LinkedList<>(); } //am I right ? I know I am an asshole.. – ErnestL1n Jul 01 '20 at 12:09
  • Correct, you could also call the `Node(int, List)` constructor from your `Node(int)` constructor : `this(_val, new LinkedList<>());` – Lino Jul 01 '20 at 12:14
  • I just changed the construct as I added in the comment , other parts remained the same But the exception still occurs = ( I don't know why – ErnestL1n Jul 01 '20 at 12:30
  • Most probable is that `treenodequeue.poll()` returns `null` because there are no elements in the queue – Lino Jul 01 '20 at 12:50
  • oh god!!! I forgot to add treenodequeue.offer(root) below the "Node root=new Node(nodes[0])" statement ,Finally it works, Thank you for your patient answering ,really thanks a lot – ErnestL1n Jul 01 '20 at 12:55
  • You're welcome, glad that I could help – Lino Jul 01 '20 at 13:21

0 Answers0