Sum of subtree depths for every node of a given Binary Tree | C # 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 ; Driver Code ; Given Tree ; Print the result
using System ; public class GFG { static int ans ; class pair { public int first , second ; public pair ( int first , int second ) { this . first = first ; this . second = second ; } } class TreeNode { public int data ; public TreeNode left ; public TreeNode right ; } ; static TreeNode newNode ( int data ) { TreeNode Node = new TreeNode ( ) ; Node . data = data ; Node . left = null ; Node . right = null ; return ( Node ) ; } static pair sumofsubtree ( TreeNode root ) { pair p = new pair ( 1 , 0 ) ; if ( root . left != null ) { pair ptemp = sumofsubtree ( root . left ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } if ( root . right != null ) { pair ptemp = sumofsubtree ( root . right ) ; p . second += ptemp . first + ptemp . second ; p . first += ptemp . first ; } ans += p . second ; return p ; } public static void Main ( String [ ] args ) { TreeNode 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 ) ; Console . Write ( ans ) ; } }