Count balanced nodes present in a binary tree | 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 ; Insert nodes in tree ; Store the count of balanced nodes
class Node : NEW_LINE INDENT def __init__ ( self , val ) : NEW_LINE INDENT self . data = val NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def Sum ( root ) : NEW_LINE INDENT global res NEW_LINE if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT leftSubSum = Sum ( root . left ) NEW_LINE rightSubSum = Sum ( root . right ) NEW_LINE if ( root . left and root . right and leftSubSum == rightSubSum ) : NEW_LINE INDENT res += 1 NEW_LINE DEDENT return ( root . data + leftSubSum + rightSubSum ) NEW_LINE DEDENT root = Node ( 9 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . left . left = Node ( - 1 ) NEW_LINE root . left . right = Node ( 3 ) NEW_LINE root . right = Node ( 4 ) NEW_LINE root . right . right = Node ( 0 ) NEW_LINE global res NEW_LINE res = 0 NEW_LINE Sum ( root ) NEW_LINE print ( res ) NEW_LINE