codeparrot/xlcost-text-to-code huggingface dataset:
Sum of heights of all individual nodes in a binary tree | Java program to find sum of heights of all nodes in a binary tree ; A binary tree Node has data , pointer to left child and a pointer to right child ; Helper function that allocates a new Node with the given data and null left and right pointers . ; Function to sum of heights of individual Nodes Uses Inorder traversal ; Driver code
class GFG { static class Node { int data ; Node left ; Node right ; } ; static int sum ; static Node newNode ( int data ) { Node Node = new Node ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static int getTotalHeightUtil ( Node root ) { if ( root == null ) { return 0 ; } int lh = getTotalHeightUtil ( root . left ) ; int rh = getTotalHeightUtil ( root . right ) ; int h = Math . max ( lh , rh ) + 1 ; sum = sum + h ; return h ; } static int getTotalHeight ( Node root ) { sum = 0 ; getTotalHeightUtil ( root ) ; return sum ; } public static void main ( String [ ] args ) { Node root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; System . out . printf ( " Sum ▁ of ▁ heights ▁ of ▁ all ▁ Nodes ▁ = ▁ % d " , getTotalHeight ( root ) ) ; } }
Inorder Tree Traversal without Recursion | non - recursive java program for inorder traversal ; Class containing left and right child of current node and key value ; Class to print the inorder traversal ; traverse the tree ; Reach the left most Node of the curr Node ; place pointer to a tree node on the stack before traversing the node 's left subtree  ; Current must be NULL at this point ; we have visited the node and its left subtree . Now , it ' s ▁ right ▁ ▁ subtree ' s turn ; Driver program to test above functions ; creating a binary tree and entering the nodes
import java . util . Stack ; class Node { int data ; Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } class BinaryTree { Node root ; void inorder ( ) { if ( root == null ) return ; Stack < Node > s = new Stack < Node > ( ) ; Node curr = root ; while ( curr != null || s . size ( ) > 0 ) { while ( curr != null ) { s . push ( curr ) ; curr = curr . left ; } curr = s . pop ( ) ; System . out . print ( curr . data + " ▁ " ) ; curr = curr . right ; } } public static void main ( String args [ ] ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 1 ) ; tree . root . left = new Node ( 2 ) ; tree . root . right = new Node ( 3 ) ; tree . root . left . left = new Node ( 4 ) ; tree . root . left . right = new Node ( 5 ) ; tree . inorder ( ) ; } }
Count all possible paths from top left to bottom right of a mXn matrix | A Java program to count all possible paths from top left to bottom right ; Returns count of possible paths to reach cell at row number m and column number n from the topmost leftmost cell ( cell at 1 , 1 ) ; Create a 2D table to store results of subproblems ; Count of paths to reach any cell in first column is 1 ; Count of paths to reach any cell in first column is 1 ; Calculate count of paths for other cells in bottom - up manner using the recursive solution ; By uncommenting the last part the code calculates the total possible paths if the diagonal Movements are allowed ; Driver program to test above function
class GFG { static int numberOfPaths ( int m , int n ) { int count [ ] [ ] = new int [ m ] [ n ] ; for ( int i = 0 ; i < m ; i ++ ) count [ i ] [ 0 ] = 1 ; for ( int j = 0 ; j < n ; j ++ ) count [ 0 ] [ j ] = 1 ; for ( int i = 1 ; i < m ; i ++ ) { for ( int j = 1 ; j < n ; j ++ ) count [ i ] [ j ] = count [ i - 1 ] [ j ] + count [ i ] [ j - 1 ] ; + count [ i - 1 ] [ j - 1 ] ; } return count [ m - 1 ] [ n - 1 ] ; } public static void main ( String args [ ] ) { System . out . println ( numberOfPaths ( 3 , 3 ) ) ; } }
Split array into two equal length subsets such that all repetitions of a number lies in a single subset | Java program for the above approach ; Function to create the frequency array of the given array arr [ ] ; Hashmap to store the frequencies ; Store freq for each element ; Get the total frequencies ; Store frequencies in subset [ ] array ; Return frequency array ; Function to check is sum N / 2 can be formed using some subset ; dp [ i ] [ j ] store the answer to form sum j using 1 st i elements ; Initialize dp [ ] [ ] with true ; Fill the subset table in the bottom up manner ; If current element is less than j ; Update current state ; Return the result ; Function to check if the given array can be split into required sets ; Store frequencies of arr [ ] ; If size of arr [ ] is odd then print " Yes " ; Check if answer is true or not ; Print the result ; Driver Code ; Given array arr [ ] ; Function Call
import java . io . * ; import java . util . * ; class GFG { private static int [ ] findSubsets ( int [ ] arr ) { HashMap < Integer , Integer > M = new HashMap < > ( ) ; for ( int i = 0 ; i < arr . length ; i ++ ) { M . put ( arr [ i ] , M . getOrDefault ( arr [ i ] , 0 ) + 1 ) ; } int [ ] subsets = new int [ M . size ( ) ] ; int i = 0 ; for ( Map . Entry < Integer , Integer > playerEntry : M . entrySet ( ) ) { subsets [ i ++ ] = playerEntry . getValue ( ) ; } return subsets ; } private static boolean subsetSum ( int [ ] subsets , int target ) { boolean [ ] [ ] dp = new boolean [ subsets . length + 1 ] [ target + 1 ] ; for ( int i = 0 ; i < dp . length ; i ++ ) dp [ i ] [ 0 ] = true ; for ( int i = 1 ; i <= subsets . length ; i ++ ) { for ( int j = 1 ; j <= target ; j ++ ) { dp [ i ] [ j ] = dp [ i - 1 ] [ j ] ; if ( j >= subsets [ i - 1 ] ) { dp [ i ] [ j ] |= dp [ i - 1 ] [ j - subsets [ i - 1 ] ] ; } } } return dp [ subsets . length ] [ target ] ; } public static void divideInto2Subset ( int [ ] arr ) { int [ ] subsets = findSubsets ( arr ) ; if ( ( arr . length ) % 2 == 1 ) { System . out . println ( " No " ) ; return ; } boolean isPossible = subsetSum ( subsets , arr . length / 2 ) ; if ( isPossible ) { System . out . println ( " Yes " ) ; } else { System . out . println ( " No " ) ; } } public static void main ( String [ ] args ) { int [ ] arr = { 2 , 1 , 2 , 3 } ; divideInto2Subset ( arr ) ; } }
Maximum Product Cutting | DP | Java program to find maximum product ; The main function that returns maximum product obtainable from a rope of length n ; Base cases ; Make a cut at different places and take the maximum of all ; Return the maximum of all values ; Driver program to test above functions
import java . io . * ; class GFG { static int maxProd ( int n ) { if ( n == 0 n == 1 ) return 0 ; int max_val = 0 ; for ( int i = 1 ; i < n ; i ++ ) max_val = Math . max ( max_val , Math . max ( i * ( n - i ) , maxProd ( n - i ) * i ) ) ; return max_val ; } public static void main ( String [ ] args ) { System . out . println ( " Maximum ▁ Product ▁ is ▁ " + maxProd ( 10 ) ) ; } }
Assembly Line Scheduling | DP | A java program to find minimum possible time by the car chassis to complete ; Utility function to find minimum of two numbers ; time taken to leave first station in line 1 ; time taken to leave first station in line 2 ; Fill tables T1 [ ] and T2 [ ] using the above given recursive relations ; Consider exit times and retutn minimum ; Driver code
import java . io . * ; class GFG { static int NUM_LINE = 2 ; static int NUM_STATION = 4 ; static int min ( int a , int b ) { return a < b ? a : b ; } static int carAssembly ( int a [ ] [ ] , int t [ ] [ ] , int e [ ] , int x [ ] ) { int T1 [ ] = new int [ NUM_STATION ] ; int T2 [ ] = new int [ NUM_STATION ] ; int i ; T1 [ 0 ] = e [ 0 ] + a [ 0 ] [ 0 ] ; T2 [ 0 ] = e [ 1 ] + a [ 1 ] [ 0 ] ; for ( i = 1 ; i < NUM_STATION ; ++ i ) { T1 [ i ] = min ( T1 [ i - 1 ] + a [ 0 ] [ i ] , T2 [ i - 1 ] + t [ 1 ] [ i ] + a [ 0 ] [ i ] ) ; T2 [ i ] = min ( T2 [ i - 1 ] + a [ 1 ] [ i ] , T1 [ i - 1 ] + t [ 0 ] [ i ] + a [ 1 ] [ i ] ) ; } return min ( T1 [ NUM_STATION - 1 ] + x [ 0 ] , T2 [ NUM_STATION - 1 ] + x [ 1 ] ) ; } public static void main ( String [ ] args ) { int a [ ] [ ] = { { 4 , 5 , 3 , 2 } , { 2 , 10 , 1 , 4 } } ; int t [ ] [ ] = { { 0 , 7 , 4 , 5 } , { 0 , 9 , 2 , 8 } } ; int e [ ] = { 10 , 12 } , x [ ] = { 18 , 7 } ; System . out . println ( carAssembly ( a , t , e , x ) ) ; } }
Longest Common Substring | DP | Java implementation of finding length of longest Common substring using Dynamic Programming ; Returns length of longest common substring of X [ 0. . m - 1 ] and Y [ 0. . n - 1 ] ; Create a table to store lengths of longest common suffixes of substrings . Note that LCSuff [ i ] [ j ] contains length of longest common suffix of X [ 0. . i - 1 ] and Y [ 0. . j - 1 ] . The first row and first column entries have no logical meaning , they are used only for simplicity of program ; To store length of the longest common substring ; Following steps build LCSuff [ m + 1 ] [ n + 1 ] in bottom up fashion ; Driver Code
class GFG { static int LCSubStr ( char X [ ] , char Y [ ] , int m , int n ) { int LCStuff [ ] [ ] = new int [ m + 1 ] [ n + 1 ] ; int result = 0 ; for ( int i = 0 ; i <= m ; i ++ ) { for ( int j = 0 ; j <= n ; j ++ ) { if ( i == 0 j == 0 ) LCStuff [ i ] [ j ] = 0 ; else if ( X [ i - 1 ] == Y [ j - 1 ] ) { LCStuff [ i ] [ j ] = LCStuff [ i - 1 ] [ j - 1 ] + 1 ; result = Integer . max ( result , LCStuff [ i ] [ j ] ) ; } else LCStuff [ i ] [ j ] = 0 ; } } return result ; } public static void main ( String [ ] args ) { String X = " OldSite : GeeksforGeeks . org " ; String Y = " NewSite : GeeksQuiz . com " ; int m = X . length ( ) ; int n = Y . length ( ) ; System . out . println ( LCSubStr ( X . toCharArray ( ) , Y . toCharArray ( ) , m , n ) ) ; } }
Minimum insertions to form a palindrome | DP | A Java solution for Dynamic Programming based program to find minimum number insertions needed to make a string palindrome ; A DP function to find minimum number of insertions ; Create a table of size n * n . table [ i ] [ j ] will store minimum number of insertions needed to convert str [ i . . j ] to a palindrome . ; Fill the table ; Return minimum number of insertions for str [ 0. . n - 1 ] ; Driver program to test above function .
import java . util . Arrays ; class GFG { static int findMinInsertionsDP ( char str [ ] , int n ) { int table [ ] [ ] = new int [ n ] [ n ] ; int l , h , gap ; for ( gap = 1 ; gap < n ; ++ gap ) for ( l = 0 , h = gap ; h < n ; ++ l , ++ h ) table [ l ] [ h ] = ( str [ l ] == str [ h ] ) ? table [ l + 1 ] [ h - 1 ] : ( Integer . min ( table [ l ] [ h - 1 ] , table [ l + 1 ] [ h ] ) + 1 ) ; return table [ 0 ] [ n - 1 ] ; } public static void main ( String args [ ] ) { String str = " geeks " ; System . out . println ( findMinInsertionsDP ( str . toCharArray ( ) , str . length ( ) ) ) ; } }
Maximum Subarray Sum using Divide and Conquer algorithm | A Divide and Conquer based Java program for maximum subarray sum problem ; Find the maximum possible sum in arr [ ] such that arr [ m ] is part of it ; Include elements on left of mid . ; Include elements on right of mid ; Return sum of elements on left and right of mid returning only left_sum + right_sum will fail for [ - 2 , 1 ] ; Returns sum of maximum sum subarray in aa [ l . . h ] ; Base Case : Only one element ; Find middle point ; Return maximum of following three possible cases : a ) Maximum subarray sum in left half b ) Maximum subarray sum in right half c ) Maximum subarray sum such that the subarray crosses the midpoint ; Driver program to test maxSubArraySum
import java . util . * ; class GFG { static int maxCrossingSum ( int arr [ ] , int l , int m , int h ) { int sum = 0 ; int left_sum = Integer . MIN_VALUE ; for ( int i = m ; i >= l ; i -- ) { sum = sum + arr [ i ] ; if ( sum > left_sum ) left_sum = sum ; } sum = 0 ; int right_sum = Integer . MIN_VALUE ; for ( int i = m + 1 ; i <= h ; i ++ ) { sum = sum + arr [ i ] ; if ( sum > right_sum ) right_sum = sum ; } return Math . max ( left_sum + right_sum , Math . max ( left_sum , right_sum ) ) ; } static int maxSubArraySum ( int arr [ ] , int l , int h ) { if ( l == h ) return arr [ l ] ; int m = ( l + h ) / 2 ; return Math . max ( Math . max ( maxSubArraySum ( arr , l , m ) , maxSubArraySum ( arr , m + 1 , h ) ) , maxCrossingSum ( arr , l , m , h ) ) ; } public static void main ( String [ ] args ) { int arr [ ] = { 2 , 3 , 4 , 5 , 7 } ; int n = arr . length ; int max_sum = maxSubArraySum ( arr , 0 , n - 1 ) ; System . out . println ( " Maximum ▁ contiguous ▁ sum ▁ is ▁ " + max_sum ) ; } }
Largest Independent Set Problem | DP | A naive recursive implementation of Largest Independent Set problem ; A utility function to find max of two integers ; A binary tree node has data , pointer to left child and a pointer to right child ; The function returns size of the largest independent set in a given binary tree ; Calculate size excluding the current node ; Calculate size including the current node ; Return the maximum of two sizes ; A utility function to create a node ; Driver Code ; Let us construct the tree given in the above diagram
class GFG { static int max ( int x , int y ) { return ( x > y ) ? x : y ; } static class Node { int data ; Node left , right ; } ; static int LISS ( Node root ) { if ( root == null ) return 0 ; int size_excl = LISS ( root . left ) + LISS ( root . right ) ; int size_incl = 1 ; if ( root . left != null ) size_incl += LISS ( root . left . left ) + LISS ( root . left . right ) ; if ( root . right != null ) size_incl += LISS ( root . right . left ) + LISS ( root . right . right ) ; return max ( size_incl , size_excl ) ; } static Node newNode ( int data ) { Node temp = new Node ( ) ; temp . data = data ; temp . left = temp . right = null ; return temp ; } public static void main ( String args [ ] ) { Node root = newNode ( 20 ) ; root . left = newNode ( 8 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 12 ) ; root . left . right . left = newNode ( 10 ) ; root . left . right . right = newNode ( 14 ) ; root . right = newNode ( 22 ) ; root . right . right = newNode ( 25 ) ; System . out . println ( " Size ▁ of ▁ the ▁ Largest " + " ▁ Independent ▁ Set ▁ is ▁ " + LISS ( root ) ) ; } }
Program to find amount of water in a given glass | Program to find the amount / of water in j - th glass of i - th row ; Returns the amount of water in jth glass of ith row ; A row number i has maximum i columns . So input column number must be less than i ; There will be i * ( i + 1 ) / 2 glasses till ith row ( including ith row ) ; Put all water in first glass ; Now let the water flow to the downward glasses till the row number is less than or / equal to i ( given row ) correction : X can be zero for side glasses as they have lower rate to fill ; Fill glasses in a given row . Number of columns in a row is equal to row number ; Get the water from current glass ; Keep the amount less than or equal to capacity in current glass ; Get the remaining amount ; Distribute the remaining amount to the down two glasses ; The index of jth glass in ith row will be i * ( i - 1 ) / 2 + j - 1 ; Driver Code ; Total amount of water
import java . lang . * ; class GFG { static float findWater ( int i , int j , float X ) { if ( j > i ) { System . out . println ( " Incorrect ▁ Input " ) ; System . exit ( 0 ) ; } int ll = Math . round ( ( i * ( i + 1 ) ) ) ; float [ ] glass = new float [ ll + 2 ] ; int index = 0 ; glass [ index ] = X ; for ( int row = 1 ; row <= i ; ++ row ) { for ( int col = 1 ; col <= row ; ++ col , ++ index ) { X = glass [ index ] ; glass [ index ] = ( X >= 1.0f ) ? 1.0f : X ; X = ( X >= 1.0f ) ? ( X - 1 ) : 0.0f ; glass [ index + row ] += X / 2 ; glass [ index + row + 1 ] += X / 2 ; } } return glass [ ( int ) ( i * ( i - 1 ) / 2 + j - 1 ) ] ; } public static void main ( String [ ] args ) { int i = 2 , j = 2 ; float X = 2.0f ; System . out . println ( " Amount ▁ of ▁ water ▁ in ▁ jth ▁ " + " glass ▁ of ▁ ith ▁ row ▁ is : ▁ " + findWater ( i , j , X ) ) ; } }
Program to find amount of water in a given glass | Program to find the amount / of water in j - th glass of i - th row ; class Triplet which stores curr row curr col and curr rem - water of every glass ; Returns the amount of water in jth glass of ith row ; stores how much amount of water present in every glass ; store Triplet i . e curr - row , curr - col , rem - water ; we take the center of the first row for the location of the first glass ; this while loop runs unless the queue is not empty ; First we remove the Triplet from the queue ; as we know we have to calculate the amount of water in jth glass of ith row . so first we check if we find solutions for the the every glass of i 'th row.  so, if we have calculated the result  then we break the loop  and return our answer ; As we know maximum capacity of every glass is 1 unit . so first we check the capacity of curr glass is full or not . ; calculate the remaining capacity of water for curr glass ; if the remaining capacity of water for curr glass is greater than then the remaining capacity of tatal water then we put all remaining water into curr glass ; if remaining capacity of tatal water is not equal to zero then we add left and right glass of the next row and gives half capacity of tatal water to both the glass ; return the result for jth glass of ith row ; Driver Code ; Total amount of water
import java . io . * ; import java . util . * ; class Triplet { int row ; int col ; double rem_water ; Triplet ( int row , int col , double rem_water ) { this . row = row ; this . col = col ; this . rem_water = rem_water ; } } class GFG { public static double findWater ( int i , int j , int totalWater ) { double dp [ ] [ ] = new double [ i + 1 ] [ 2 * i + 1 ] ; Queue < Triplet > queue = new LinkedList < > ( ) ; queue . add ( new Triplet ( 0 , i , totalWater ) ) ; while ( ! queue . isEmpty ( ) ) { Triplet curr = queue . remove ( ) ; if ( curr . row == i ) break ; if ( dp [ curr . row ] [ curr . col ] != 1.0 ) { double rem_water = 1 - dp [ curr . row ] [ curr . col ] ; if ( rem_water > curr . rem_water ) { dp [ curr . row ] [ curr . col ] += curr . rem_water ; curr . rem_water = 0 ; } else { dp [ curr . row ] [ curr . col ] += rem_water ; curr . rem_water -= rem_water ; } } if ( curr . rem_water != 0 ) { queue . add ( new Triplet ( curr . row + 1 , curr . col - 1 , curr . rem_water / 2.0 ) ) ; queue . add ( new Triplet ( curr . row + 1 , curr . col + 1 , curr . rem_water / 2.0 ) ) ; } } return dp [ i - 1 ] [ 2 * j - 1 ] ; } public static void main ( String [ ] args ) { int i = 2 , j = 2 ; int totalWater = 2 ; System . out . print ( " Amount ▁ of ▁ water ▁ in ▁ jth ▁ glass ▁ of ▁ ith ▁ row ▁ is : " ) ; System . out . format ( " % .6f " , findWater ( i , j , totalWater ) ) ; } }
Maximum Length Chain of Pairs | DP | Java program for above approach ; This function assumes that arr [ ] is sorted in increasing order according the first ( or smaller ) values in pairs . ; Initialize MCL ( max chain length ) values for all indexes ; Compute optimized chain length values in bottom up manner ; Pick maximum of all MCL values ; Driver program to test above function
class Pair { int a ; int b ; public Pair ( int a , int b ) { this . a = a ; this . b = b ; } static int maxChainLength ( Pair arr [ ] , int n ) { int i , j , max = 0 ; int mcl [ ] = new int [ n ] ; for ( i = 0 ; i < n ; i ++ ) mcl [ i ] = 1 ; for ( i = 1 ; i < n ; i ++ ) for ( j = 0 ; j < i ; j ++ ) if ( arr [ i ] . a > arr [ j ] . b && mcl [ i ] < mcl [ j ] + 1 ) mcl [ i ] = mcl [ j ] + 1 ; for ( i = 0 ; i < n ; i ++ ) if ( max < mcl [ i ] ) max = mcl [ i ] ; return max ; } public static void main ( String [ ] args ) { Pair arr [ ] = new Pair [ ] { new Pair ( 5 , 24 ) , new Pair ( 15 , 25 ) , new Pair ( 27 , 40 ) , new Pair ( 50 , 60 ) } ; System . out . println ( "Length of maximum size chain is " + maxChainLength ( arr , arr . length ) ) ; } }
Palindrome Partitioning | DP | Java Code for Palindrome Partitioning Problem ; Returns the minimum number of cuts needed to partition a string such that every part is a palindrome ; Get the length of the string ; Create two arrays to build the solution in bottom up manner C [ i ] [ j ] = Minimum number of cuts needed for palindrome partitioning of substring str [ i . . j ] P [ i ] [ j ] = true if substring str [ i . . j ] is palindrome , else false Note that C [ i ] [ j ] is 0 if P [ i ] [ j ] is true ; different looping variables ; Every substring of length 1 is a palindrome ; L is substring length . Build the solution in bottom up manner by considering all substrings of length starting from 2 to n . The loop structure is same as Matrix Chain Multiplication problem ( See https : www . geeksforgeeks . org / matrix - chain - multiplication - dp - 8 / ) ; For substring of length L , set different possible starting indexes ; Set ending index ; If L is 2 , then we just need to compare two characters . Else need to check two corner characters and value of P [ i + 1 ] [ j - 1 ] ; IF str [ i . . j ] is palindrome , then C [ i ] [ j ] is 0 ; Make a cut at every possible localtion starting from i to j , and get the minimum cost cut . ; Return the min cut value for complete string . i . e . , str [ 0. . n - 1 ] ; Driver program to test above function
public class GFG { static int minPalPartion ( String str ) { int n = str . length ( ) ; int [ ] [ ] C = new int [ n ] [ n ] ; boolean [ ] [ ] P = new boolean [ n ] [ n ] ; int i , j , k , L ; for ( i = 0 ; i < n ; i ++ ) { P [ i ] [ i ] = true ; C [ i ] [ i ] = 0 ; } for ( L = 2 ; L <= n ; L ++ ) { for ( i = 0 ; i < n - L + 1 ; i ++ ) { j = i + L - 1 ; if ( L == 2 ) P [ i ] [ j ] = ( str . charAt ( i ) == str . charAt ( j ) ) ; else P [ i ] [ j ] = ( str . charAt ( i ) == str . charAt ( j ) ) && P [ i + 1 ] [ j - 1 ] ; if ( P [ i ] [ j ] == true ) C [ i ] [ j ] = 0 ; else { C [ i ] [ j ] = Integer . MAX_VALUE ; for ( k = i ; k <= j - 1 ; k ++ ) C [ i ] [ j ] = Integer . min ( C [ i ] [ j ] , C [ i ] [ k ] + C [ k + 1 ] [ j ] + 1 ) ; } } } return C [ 0 ] [ n - 1 ] ; } public static void main ( String args [ ] ) { String str = " ababbbabbababa " ; System . out . println ( " Min ▁ cuts ▁ needed ▁ for ▁ " + " Palindrome ▁ Partitioning ▁ is ▁ " + minPalPartion ( str ) ) ; } }
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 ; structure of a node of binary tree ; function to get a new node ; allocate space ; put in the data ; function to count subtress that sum up to a given value x ; if tree is empty ; sum of nodes in the left subtree ; sum of nodes in the right subtree ; sum of nodes in the subtree rooted with ' root . data ' ; if true ; return subtree 's nodes sum ; utility function to count subtress that sum up to a given value x ; if tree is empty ; sum of nodes in the left subtree ; sum of nodes in the right subtree ; if tree 's nodes sum == x ; required count of subtrees ; Driver Code ; binary tree creation 5 / \ - 10 3 / \ / \ 9 8 - 4 7
import java . util . * ; class GFG { static class Node { int data ; Node left , right ; } static class INT { int v ; INT ( int a ) { v = a ; } } static Node getNode ( int data ) { Node newNode = new Node ( ) ; newNode . data = data ; newNode . left = newNode . right = null ; return newNode ; } static int countSubtreesWithSumX ( Node root , INT count , int x ) { if ( root == null ) return 0 ; int ls = countSubtreesWithSumX ( root . left , count , x ) ; int rs = countSubtreesWithSumX ( root . right , count , x ) ; int sum = ls + rs + root . data ; if ( sum == x ) count . v ++ ; return sum ; } static int countSubtreesWithSumXUtil ( Node root , int x ) { if ( root == null ) return 0 ; INT count = new INT ( 0 ) ; int ls = countSubtreesWithSumX ( root . left , count , x ) ; int rs = countSubtreesWithSumX ( root . right , count , x ) ; if ( ( ls + rs + root . data ) == x ) count . v ++ ; return count . v ; } public static void main ( String args [ ] ) { Node root = getNode ( 5 ) ; root . left = getNode ( - 10 ) ; root . right = getNode ( 3 ) ; root . left . left = getNode ( 9 ) ; root . left . right = getNode ( 8 ) ; root . right . left = getNode ( - 4 ) ; root . right . right = getNode ( 7 ) ; int x = 7 ; System . out . println ( " Count ▁ = ▁ " + countSubtreesWithSumXUtil ( root , x ) ) ; } }