Sum of subtree depths for every node of a given Binary Tree | JavaScript program for the above approach ; Binary tree node ; Function to allocate a new node with the given data and null in its left and right pointers ; DFS function to calculate the sum of depths of all subtrees depth sum ; Store total number of node in its subtree and total sum of depth in its subtree ; Check if left is not null ; Call recursively the DFS function for left child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of noded in left subtree ; Check if right is not null ; Call recursively the DFS function for right child ; Increment the sum of depths by ptemp . first + p . temp . first ; Increment p . first by count of nodes in right subtree ; Increment the result by total sum of depth in current subtree ; Return p ; Given Tree ; Print the result
var ans ; class pair { constructor ( first , second ) { this . first = first ; this . second = second ; } } class TreeNode { constructor ( ) { this . data = 0 ; this . left = null ; this . right = null ; } } function newNode ( data ) { var Node = new TreeNode ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return Node ; } function sumofsubtree ( root ) { var p = new pair ( 1 , 0 ) ; if ( root . left != null ) { var ptemp = sumofsubtree ( root . left ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } if ( root . right != null ) { var ptemp = sumofsubtree ( root . right ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } ans += p . second ; return p ; } var root = newNode ( 1 ) ; root . left = newNode ( 2 ) ; root . right = newNode ( 3 ) ; root . left . left = newNode ( 4 ) ; root . left . right = newNode ( 5 ) ; root . right . left = newNode ( 6 ) ; root . right . right = newNode ( 7 ) ; root . left . left . left = newNode ( 8 ) ; root . left . left . right = newNode ( 9 ) ; ans = 0 ; sumofsubtree ( root ) ; document . write ( ans ) ;