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 ; Passing sum as accumulator and implementing pass by reference of sum variable ; Pass in a sum variable as an accumulator ; Check whether this node is a leaf node and is left . ; Pass true for left and false for right ; A wrapper over above recursive function ; use the above recursive function to evaluate sum ; Driver program ; Let us construct the Binary Tree shown in the above figure
using System ; public class Node { public int data ; public Node left , right ; public Node ( int item ) { data = item ; left = right = null ; } } public class Sum { public int sum = 0 ; } public class BinaryTree { public Node root ; public virtual void leftLeavesSumRec ( Node node , bool isleft , Sum summ ) { if ( node == null ) { return ; } if ( node . left == null && node . right == null && isleft ) { summ . sum = summ . sum + node . data ; } leftLeavesSumRec ( node . left , true , summ ) ; leftLeavesSumRec ( node . right , false , summ ) ; } public virtual int leftLeavesSum ( Node node ) { Sum suum = new Sum ( ) ; leftLeavesSumRec ( node , false , suum ) ; return suum . sum ; } 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 ) ) ; } }