Sum of all leaf nodes of binary tree | C # program to find sum of all leaf nodes of binary tree ; user define class node ; constructor ; utility function which calculates sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; driver program ; construct binary tree ; variable to store sum of leaf nodes
using System ; public class GFG { public class Node { public int data ; public Node left , right ; public Node ( int data ) { this . data = data ; left = null ; right = null ; } } public static int sum ; public static void leafSum ( Node root ) { if ( root == null ) { return ; } if ( root . left == null && root . right == null ) { sum += root . data ; } leafSum ( root . left ) ; leafSum ( root . right ) ; } public static void Main ( string [ ] args ) { Node root = new Node ( 1 ) ; root . left = new Node ( 2 ) ; root . left . left = new Node ( 4 ) ; root . left . right = new Node ( 5 ) ; root . right = new Node ( 3 ) ; root . right . right = new Node ( 7 ) ; root . right . left = new Node ( 6 ) ; root . right . left . right = new Node ( 8 ) ; sum = 0 ; leafSum ( root ) ; Console . WriteLine ( sum ) ; } }