Find sum of all left leaves in a given Binary Tree | A C ++ program to find sum of all left leaves ; A binary tree Node has key , pointer to left and right children ; Helper function that allocates a new node with the given data and NULL left and right pointer . ; Pass in a sum variable as an accumulator ; Check whether this node is a leaf node and is left . ; Pass 1 for left and 0 for right ; A wrapper over above recursive function ; use the above recursive function to evaluate sum ; Driver program to test above functions ; Let us construct the Binary Tree shown in the above figure
#include <bits/stdc++.h> NEW_LINE using namespace std ; struct Node { int key ; struct Node * left , * right ; } ; Node * newNode ( char k ) { Node * node = new Node ; node -> key = k ; node -> right = node -> left = NULL ; return node ; } void leftLeavesSumRec ( Node * root , bool isleft , int * sum ) { if ( ! root ) return ; if ( ! root -> left && ! root -> right && isleft ) * sum += root -> key ; leftLeavesSumRec ( root -> left , 1 , sum ) ; leftLeavesSumRec ( root -> right , 0 , sum ) ; } int leftLeavesSum ( Node * root ) { int sum = 0 ; leftLeavesSumRec ( root , 0 , & sum ) ; return sum ; } int main ( ) { int sum = 0 ; struct Node * root = newNode ( 20 ) ; root -> left = newNode ( 9 ) ; root -> right = newNode ( 49 ) ; root -> right -> left = newNode ( 23 ) ; root -> right -> right = newNode ( 52 ) ; root -> right -> right -> left = newNode ( 50 ) ; root -> left -> left = newNode ( 5 ) ; root -> left -> right = newNode ( 12 ) ; root -> left -> right -> right = newNode ( 12 ) ; cout << " Sum ▁ of ▁ left ▁ leaves ▁ is ▁ " << leftLeavesSum ( root ) << endl ; return 0 ; }