import java.util.*; public class Main { public static void main(String args[]) { Scanner obj = new Scanner(System.in); bt tree = new bt(); int k = obj.nextInt(); System.out.println(tree.sum(k)); } } class bt { public static Scanner obj = new Scanner(System.in); class node { int data ; node left; node right; public node(int val) {data = val; left = null; right = null;} } private node root; public bt() {root = takeinput();} private node takeinput() { int a = obj.nextInt(); node temp = new node(a); int nc=obj.nextInt(); if(nc==1) { temp.left = takeinput(); } else if(nc==2) { temp.left = takeinput(); temp.right= takeinput(); } return temp; } public int sum(int des) { return sum(root,0,des); } private int sum(node parent ,int lvl,int des) { if(lvl ==des) {return parent.data;} if(parent.left!=null && parent.right==null) {int s = sum(parent.left,lvl+1,des); return s;} else if(parent.right!=null && parent.left ==null) {int d = sum(parent.right,lvl+1,des); return d;} else if(parent.left!=null && parent.right!=null) {int s = sum(parent.left,lvl+1,des); int d = sum(parent.right,lvl+1,des); return s+d; } return 0; } }
problem:- Exception in thread “main” java.util.NoSuchElementException if i am using int k = 2 ; then the output is correct but if i am taking k as input , then it is showing this error what to do???
Trees -- Find sum at level K
@diwakargour121,
There was an error of scanner class object. https://ide.codingblocks.com/s/170195 here is the corrected code. I have taken input of k in the bt constructor itself.
I have done this too and i know it’s working , but i am not getting what is wrong in making two object of scanner in different classes and then taking the value of k in main class
Can we make only one class of Scanner?
What to do if we have to take input in both the classes
@diwakargour121,
See this solution, here I have passed the scanner object from main to bt class https://ide.codingblocks.com/s/170411. There is a synchronization error of scanner object on online IDEs, hence the error. To avoid this either take all input in one class or pass the original scanner object