i am unable to pass 2 test case. Can you please check
Total Subtree with given sum
import java.util.*; public class Main { public static class Node{ int data; Node left,right; Node(int d) { data =d; this.left = this.right = null; } } static int[] treeArray = new int[1000]; //static int sumNum = 0; public static void main (String args[]) { Scanner scan = new Scanner(System.in); int n = scan.nextInt(); int j = 0; while(j < n) { String inputString = scan.next(); int sumNum = scan.nextInt(); convertStringToInt(inputString); Node root = createBinaryTree(); int totalCount = countSubTree(root,sumNum); System.out.println(totalCount); j++; } } private static void convertStringToInt(String inputString) { treeArray = Arrays.stream(inputString.split(" ")) .mapToInt(Integer::valueOf) .toArray(); } private static int countSubTree(Node root, int sumNum) { if(root ==null) return 0; int ans = 0; if(sumTree(root) == sumNum){ ans =1; } int leftSubTree = countSubTree(root.left, sumNum); int rightSubTree = countSubTree(root.right, sumNum); return ans + leftSubTree + rightSubTree; } private static int sumTree(Node root) { if(root ==null) return 0; int leftSum = sumTree(root.left); int rightSum = sumTree(root.right); return root.data + leftSum + rightSum; } private static Node createBinaryTree() { if((treeArray.length) ==0)return null; int num = treeArray[0]; Node root = new Node(num); int i =1; Queue q = new LinkedList<>(); q.add(root); while(!q.isEmpty() && i < treeArray.length) { Node temp = q.poll(); num = treeArray[i++]; temp.left = new Node(num); q.add( temp.left); if(i>=treeArray.length){ break; } num = treeArray[i++]; temp.right = new Node(num); q.add( temp.right); if(i>=treeArray.length){ break; } } return root; } }
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.