Count subtrees that sum up to a given value x only using single recursive function | Java program to find if there is a subtree with given sum ; Node class to create new node ; Utility function to count subtress that sum up to a given value x ; Driver Code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7
import java . io . * ; class Node { int data ; Node left ; Node right ; Node ( int data ) { this . data = data ; } } class GFG { static int count = 0 ; static Node ptr ; int countSubtreesWithSumXUtil ( Node root , int x ) { int l = 0 , r = 0 ; if ( root == null ) return 0 ; l += countSubtreesWithSumXUtil ( root . left , x ) ; r += countSubtreesWithSumXUtil ( root . right , x ) ; if ( l + r + root . data == x ) count ++ ; if ( ptr != root ) return l + root . data + r ; return count ; } public static void main ( String [ ] args ) { Node root = new Node ( 5 ) ; root . left = new Node ( - 10 ) ; root . right = new Node ( 3 ) ; root . left . left = new Node ( 9 ) ; root . left . right = new Node ( 8 ) ; root . right . left = new Node ( - 4 ) ; root . right . right = new Node ( 7 ) ; int x = 7 ; ptr = root ; System . out . println ( " Count ▁ = ▁ " + new GFG ( ) . countSubtreesWithSumXUtil ( root , x ) ) ; } }