Find sum of all left leaves in a given Binary Tree | C # program to find sum of all left leaves ; A binary tree Node has key , pointer to left and right children ; A utility function to check if a given node is leaf or not ; This function returns sum of all left leaves in a given binary tree ; Initialize result ; Update result if root is not NULL ; If left of root is NULL , then add key of left child ; Else recur for left child of root ; Recur for right child of root and update res ; return result ; Driver program
using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class BinaryTree { public Node root ; public virtual bool isLeaf ( Node node ) { if ( node == null ) { return false ; } if ( node . left == null && node . right == null ) { return true ; } return false ; } public virtual int leftLeavesSum ( Node node ) { int res = 0 ; if ( node != null ) { if ( isLeaf ( node . left ) ) { res += node . left . data ; } else { res += leftLeavesSum ( node . left ) ; } res += leftLeavesSum ( node . right ) ; } return res ; } public static void Main ( string [ ] args ) { BinaryTree tree = new BinaryTree ( ) ; tree . root = new Node ( 20 ) ; tree . root . left = new Node ( 9 ) ; tree . root . right = new Node ( 49 ) ; tree . root . left . right = new Node ( 12 ) ; tree . root . left . left = new Node ( 5 ) ; tree . root . right . left = new Node ( 23 ) ; tree . root . right . right = new Node ( 52 ) ; tree . root . left . right . right = new Node ( 12 ) ; tree . root . right . right . left = new Node ( 50 ) ; Console . WriteLine ( " The ▁ sum ▁ of ▁ leaves ▁ is ▁ " + tree . leftLeavesSum ( tree . root ) ) ; } }