Find sum of all left leaves in a given Binary Tree | C # program to find sum of all left leaves ; A binary tree node ; constructor to create a new Node ; Return the sum of left leaf nodes ; A queue of pairs to do bfs traversal and keep track if the node is a left or right child if bool value is true then it is a left child . ; do bfs traversal ; if temp is a leaf node and left child of its parent ; if it is not leaf then push its children nodes into queue ; bool value is true here because it is left child of its parent ; bool value is false here because it is right child of its parent ; Driver Code
using System ; using System . Collections . Generic ; public class GFG { public class Node { public int key ; public Node left , right ; public Node ( int key_ ) { key = key_ ; left = null ; right = null ; } } ; public class pair { public Node first ; public bool second ; public pair ( Node first , bool second ) { this . first = first ; this . second = second ; } } static int sumOfLeftLeaves ( Node root ) { if ( root == null ) return 0 ; Queue < pair > q = new Queue < pair > ( ) ; q . Enqueue ( new pair ( root , false ) ) ; int sum = 0 ; while ( q . Count != 0 ) { Node temp = q . Peek ( ) . first ; bool is_left_child = q . Peek ( ) . second ; q . Dequeue ( ) ; if ( is_left_child ) sum = sum + temp . key ; if ( temp . left != null && temp . right != null && is_left_child ) sum = sum - temp . key ; if ( temp . left != null ) { q . Enqueue ( new pair ( temp . left , true ) ) ; } if ( temp . right != null ) { q . Enqueue ( new pair ( temp . right , false ) ) ; } } return sum ; } public static void Main ( String [ ] args ) { Node root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . right . right . left = new Node ( 50 ) ; root . left . left = new Node ( 5 ) ; root . left . right = new Node ( 12 ) ; root . left . right . right = new Node ( 12 ) ; Console . Write ( " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " + sumOfLeftLeaves ( root ) + " STRNEWLINE " ) ; } }