Find sum of all left leaves in a given Binary Tree | 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 ; Let us construct the Binary Tree shown in the above figure
class Node { constructor ( item ) { this . data = item ; this . left = this . right = null ; } } class Sum { constructor ( ) { this . sum = 0 ; } } var root ; function leftLeavesSumRec ( node , isleft , 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 ) ; } function leftLeavesSum ( node ) { suum = new Sum ( ) ; leftLeavesSumRec ( node , false , suum ) ; return suum . sum ; } root = new Node ( 20 ) ; root . left = new Node ( 9 ) ; root . right = new Node ( 49 ) ; root . left . right = new Node ( 12 ) ; root . left . left = new Node ( 5 ) ; root . right . left = new Node ( 23 ) ; root . right . right = new Node ( 52 ) ; root . left . right . right = new Node ( 12 ) ; root . right . right . left = new Node ( 50 ) ; document . write ( " " + leftLeavesSum ( root ) ) ;