I am getting this error in run time :-
Exception in thread “main” java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1485)
Code :-
import java.util.*;
import java.util.LinkedList;
public class Main
{
public static class GenericTree
{
private class Node
{
int data;
ArrayList children;
Node()
{
this.children=new ArrayList<>();
}
Node(int data)
{
this.data=data;
this.children=new ArrayList<>();
}
}
private Node root;
private int size;
private static Scanner sc=new Scanner(System.in);
GenericTree()
{
this.root=takeInput(null);
}
private Node takeInput (Node parent)
{
Node n=new Node(sc.nextInt());
this.size++;
int children=sc.nextInt();
for(int i=1;i<=children;i++)
{
Node child=takeInput(n);
n.children.add(child);
}
return n;
}
public int levelsum(int target)
{
LinkedList <Node> queue=new LinkedList<>();
int level=0;
queue.add(root);
if(target==0)
return root.data;
while(!queue.isEmpty())
{
int size=queue.size();
if(level==target)
{
int sum=0;
while(!queue.isEmpty())
{
sum+=(queue.remove()).data;
}
return sum;
}
while(size-->=0)
{
Node node=queue.remove();
for(int j=0;j<node.children.size();j++)
{
queue.add(node.children.get(j));
}
size--;
}
level++;
}
return 0;
}
}
public static void main(String[] args)
{
Scanner sc=new Scanner (System.in);
GenericTree g=new GenericTree();
int k=sc.nextInt();
System.out.print(g.levelsum(k));
}
}