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 boolean 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 ; boolean value is true here because it is left child of its parent ; boolean value is false here because it is right child of its parent ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; class Node { public : int key ; Node * left , * right ; Node ( int key_ ) { key = key_ ; left = NULL ; right = NULL ; } } ; int sumOfLeftLeaves ( Node * root ) { if ( root == NULL ) return 0 ; queue < pair < Node * , bool > > q ; q . push ( { root , 0 } ) ; int sum = 0 ; while ( ! q . empty ( ) ) { Node * temp = q . front ( ) . first ; bool is_left_child = q . front ( ) . second ; q . pop ( ) ; if ( ! temp -> left && ! temp -> right && is_left_child ) sum = sum + temp -> key ; if ( temp -> left ) { q . push ( { temp -> left , 1 } ) ; } if ( temp -> right ) { q . push ( { temp -> right , 0 } ) ; } } return sum ; } int main ( ) { 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 ) ; cout << " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " << sumOfLeftLeaves ( root ) << endl ; return 0 ; }