Find sum of all left leaves in a given Binary Tree | A Binary tree node ; A utility function to check if a given node is leaf or not ; This function return sum of all left leaves in a given binary tree ; Initialize result ; Update result if root is not None ; If left of root is None , then add key of left child ; Else recur for left child of root ; Recur for right child of root and update res ; return result ; Driver program to test above function
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 isLeaf ( node ) : NEW_LINE INDENT if node is None : NEW_LINE INDENT return False NEW_LINE DEDENT if node . left is None and node . right is None : NEW_LINE INDENT return True NEW_LINE DEDENT return False NEW_LINE DEDENT def leftLeavesSum ( root ) : NEW_LINE INDENT res = 0 NEW_LINE if root is not None : NEW_LINE INDENT if isLeaf ( root . left ) : NEW_LINE INDENT res += root . left . key NEW_LINE DEDENT else : NEW_LINE INDENT res += leftLeavesSum ( root . left ) NEW_LINE DEDENT res += leftLeavesSum ( root . right ) NEW_LINE DEDENT return res NEW_LINE DEDENT root = Node ( 20 ) NEW_LINE root . left = Node ( 9 ) NEW_LINE root . right = Node ( 49 ) NEW_LINE root . right . left = Node ( 23 ) NEW_LINE root . right . right = Node ( 52 ) NEW_LINE root . right . right . left = Node ( 50 ) NEW_LINE root . left . left = Node ( 5 ) NEW_LINE root . left . right = Node ( 12 ) NEW_LINE root . left . right . right = Node ( 12 ) NEW_LINE print " Sum ▁ of ▁ left ▁ leaves ▁ is " , leftLeavesSum ( root ) NEW_LINE