Find sum of all left leaves in a given Binary Tree | Python3 program to find sum of all left leaves ; A binary tree 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
from collections import deque NEW_LINE class Node : NEW_LINE INDENT def __init__ ( self , x ) : NEW_LINE INDENT self . key = x NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def sumOfLeftLeaves ( root ) : NEW_LINE INDENT if ( root == None ) : NEW_LINE INDENT return 0 NEW_LINE DEDENT q = deque ( ) NEW_LINE q . append ( [ root , 0 ] ) NEW_LINE sum = 0 NEW_LINE while ( len ( q ) > 0 ) : NEW_LINE INDENT temp = q [ 0 ] [ 0 ] NEW_LINE is_left_child = q [ 0 ] [ 1 ] NEW_LINE q . popleft ( ) NEW_LINE if ( not temp . left and not temp . right and is_left_child ) : NEW_LINE INDENT sum = sum + temp . key NEW_LINE DEDENT if ( temp . left ) : NEW_LINE INDENT q . append ( [ temp . left , 1 ] ) NEW_LINE DEDENT if ( temp . right ) : NEW_LINE INDENT q . append ( [ temp . right , 0 ] ) NEW_LINE DEDENT DEDENT return sum NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT 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 " , sumOfLeftLeaves ( root ) ) NEW_LINE DEDENT