Binary Tree display, Errror-getting run time error

package Lacture12;
import java.util.Scanner;
import java.util.ArrayList;

public class GenericTree {

private class Node
{
  int data;
  ArrayList<Node> children;
  
  Node(int data)
  {
	  this.data=data;
  }
}

private Node root;
private int size;

GenericTree()
{
	Scanner s=new Scanner(System.in);
	this.root=takeInput(s,null,0);
}

private Node takeInput(Scanner s,Node parent,int ithChild)
{
	if(parent==null)
	{
		System.out.println("Enter data for root Node");
		
	}
	else
	{
		System.out.println("Enter the data for "+ithChild+"th child of "+parent.data);
	}
	
	int nodedata=s.nextInt();
	Node node=new Node(nodedata);
	this.size++;
	
	System.out.println("Enter the no of childern for "+node.data);
	int childerns=s.nextInt();
	
	//Will be executed depending on the value of childrens. 
	for(int i=0;i<childerns;++i)
	{
		Node child=takeInput(s,node,i);
		node.children.add(child);
	}
   	
	return node;

	
}

public void display()
{
	this.display(this.root);
}

private void display(Node node)
{
	//node data
	String str=node.data+"=>";
	for(int i=0;i<node.children.size();++i)
	{   //add children data of current node
		str+=node.children.get(i).data+",";
	}
	str+="END";
	
	//display the string for current node
	System.out.println(str);
	
	//display all nodes
	for(int i=0;i<node.children.size();++i)
	{
		display(node.children.get(i));
	}
}

}

Hey @rahulsharma111th,
You are getting an error in your code because you haven’t initialised the children arraylist for every node and by default it is null.

In the constructor of Node you need to initialise the children ArrayList as well.

So, instead of this:

Do this:

Hope it helps :slight_smile:

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.