Count balanced nodes present in a binary tree | JavaScript program for 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 ; Insert nodes in tree ; Store the count of balanced nodes
let res = 0 ; class Node { constructor ( val ) { this . left = null ; this . right = null ; this . data = val ; } } function Sum ( root ) { if ( root == null ) { return 0 ; } let leftSubSum = Sum ( root . left ) ; let rightSubSum = Sum ( root . right ) ; if ( root . left != null && root . right != null && leftSubSum == rightSubSum ) res += 1 ; return root . data + leftSubSum + rightSubSum ; } let 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 ) ; document . write ( res ) ;