text: Sum of specially balanced nodes from a given Binary Tree | Javascript program for the above approach ; Structure of Binary Tree ; Function to create a new node ; Return the created node ; Function to insert a node in the tree ; Left insertion ; Right insertion ; Return the root node ; Function to find sum of specially balanced nodes in the Tree ; Base Case ; Find the left subtree sum ; Find the right subtree sum ; Condition of specially balanced node ; Condition of specially balanced node ; Return the sum ; Function to build the binary tree ; Form root node of the tree ; Insert nodes into tree ; Create a new Node ; Insert the node ; Return the root of the Tree ; Function to find the sum of specially balanced nodes ; Build Tree ; Stores the sum of specially balanced node ; Function Call ; Print required sum ; Given nodes ; Given root ; Given path info of nodes from root ; Given node values ; Function Call
code: let sum ; class Node { constructor ( data ) { this . left = null ; this . right = null ; this . data = data ; } } function newnode ( data ) { let temp = new Node ( data ) ; return temp ; } function insert ( s , i , N , root , temp ) { if ( i == N ) return temp ; if ( s [ i ] == ' ' ) root . left = insert ( s , i + 1 , N , root . left , temp ) ; else root . right = insert ( s , i + 1 , N , root . right , temp ) ; return root ; } function SBTUtil ( root ) { if ( root == null ) return 0 ; if ( root . left == null && root . right == null ) return root . data ; let left = SBTUtil ( root . left ) ; let right = SBTUtil ( root . right ) ; if ( root . left != null && root . right != null ) { if ( ( left % 2 == 0 && right % 2 != 0 ) || ( left % 2 != 0 && right % 2 == 0 ) ) { sum += root . data ; } } return left + right + root . data ; } function build_tree ( R , N , str , values ) { let root = newnode ( R ) ; let i ; for ( i = 0 ; i < N - 1 ; i ++ ) { let s = str [ i ] ; let x = values [ i ] ; let temp = newnode ( x ) ; root = insert ( s , 0 , s . length , root , temp ) ; } return root ; } function speciallyBalancedNodes ( R , N , str , values ) { let root = build_tree ( R , N , str , values ) ; sum = 0 ; SBTUtil ( root ) ; document . write ( sum + " " ) ; } let N = 7 ; let R = 12 ; let str = [ " " , " " , " " , " " , " " , " " ] ; let values = [ 17 , 16 , 4 , 9 , 2 , 3 ] ; speciallyBalancedNodes ( R , N , str , values ) ;