Count balanced nodes present in a binary tree | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int data ; Node * left ; Node * right ; Node ( int val ) { data = val ; left = right = NULL ; } } ; int Sum ( Node * root , int & res ) { if ( root == NULL ) { return 0 ; } int leftSubSum = Sum ( root -> left , res ) ; int rightSubSum = Sum ( root -> right , res ) ; if ( root -> left and root -> right && leftSubSum == rightSubSum ) res += 1 ; return root -> data + leftSubSum + rightSubSum ; } int main ( ) { 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 ) ; int res = 0 ; Sum ( root , res ) ; cout << res ; }