Count balanced nodes present in a binary tree | Java program to implement the above approach ; Structure of a Tree Node ; Function to get the sum of left subtree and right subtree ; Base case ; Store the sum of left subtree ; Store the sum of right subtree ; Check if node is balanced or not ; Increase count of balanced nodes ; Return subtree sum ; Driver Code ; Insert nodes in tree ; Store the count of balanced nodes
class GFG { static int res = 0 ; static class Node { int data ; Node left ; Node right ; Node ( int val ) { data = val ; left = right = null ; } } ; static int Sum ( Node root ) { if ( root == null ) { return 0 ; } int leftSubSum = Sum ( root . left ) ; int rightSubSum = Sum ( root . right ) ; if ( root . left != null && root . right != null && leftSubSum == rightSubSum ) res += 1 ; return root . data + leftSubSum + rightSubSum ; } public static void main ( String [ ] args ) { Node root = new Node ( 9 ) ; root . left = new Node ( 2 ) ; root . left . left = new Node ( - 1 ) ; root . left . right = new Node ( 3 ) ; root . right = new Node ( 4 ) ; root . right . right = new Node ( 0 ) ; res = 0 ; Sum ( root ) ; System . out . print ( res ) ; } }