Find sum of all left leaves in a given Binary Tree | A binary tree node ; A constructor to create a new Node ; Return the sum of left leaf nodes ; Using a stack for Depth - First Traversal of the tree ; sum holds the sum of all the left leaves ; Check if currentNode 's left child is a leaf node ; if currentNode is a leaf , add its data to the sum ; Driver Code
class Node : NEW_LINE INDENT def __init__ ( self , key ) : NEW_LINE INDENT self . key = key NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumOfLeftLeaves ( root ) : NEW_LINE INDENT if ( root is None ) : NEW_LINE INDENT return NEW_LINE DEDENT stack = [ ] NEW_LINE stack . append ( root ) NEW_LINE sum = 0 NEW_LINE while len ( stack ) > 0 : NEW_LINE INDENT currentNode = stack . pop ( ) NEW_LINE if currentNode . left is not None : NEW_LINE INDENT stack . append ( currentNode . left ) NEW_LINE if currentNode . left . left is None and currentNode . left . right is None : NEW_LINE INDENT sum = sum + currentNode . left . data NEW_LINE DEDENT DEDENT if currentNode . right is not None : NEW_LINE INDENT stack . append ( currentNode . right ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT root = Tree ( 20 ) ; NEW_LINE root . left = Tree ( 9 ) ; NEW_LINE root . right = Tree ( 49 ) ; NEW_LINE root . right . left = Tree ( 23 ) ; NEW_LINE root . right . right = Tree ( 52 ) ; NEW_LINE root . right . right . left = Tree ( 50 ) ; NEW_LINE root . left . left = Tree ( 5 ) ; NEW_LINE root . left . right = Tree ( 12 ) ; NEW_LINE root . left . right . right = Tree ( 12 ) ; NEW_LINE print ( ' Sum ▁ of ▁ left ▁ leaves ▁ is ▁ { } ' . format ( sumOfLeftLeaves ( root ) ) ) NEW_LINE