Sum of all leaf nodes of binary tree | Class for node creation ; constructor ; Utility function to calculate the sum of all leaf nodes ; add root data to sum if root is a leaf node ; propagate recursively in left and right subtree ; Binary tree Fromation ; Variable to store the sum of leaf nodes
class Node : NEW_LINE INDENT def __init__ ( self , data ) : NEW_LINE INDENT self . data = data NEW_LINE self . left = None NEW_LINE self . right = None NEW_LINE DEDENT DEDENT def leafSum ( root ) : NEW_LINE INDENT global total NEW_LINE if root is None : NEW_LINE INDENT return NEW_LINE DEDENT if ( root . left is None and root . right is None ) : NEW_LINE INDENT total += root . data NEW_LINE DEDENT leafSum ( root . left ) NEW_LINE leafSum ( root . right ) NEW_LINE DEDENT if __name__ == ' _ _ main _ _ ' : NEW_LINE INDENT root = Node ( 1 ) NEW_LINE root . left = Node ( 2 ) NEW_LINE root . left . left = Node ( 4 ) NEW_LINE root . left . right = Node ( 5 ) NEW_LINE root . right = Node ( 3 ) NEW_LINE root . right . right = Node ( 7 ) NEW_LINE root . right . left = Node ( 6 ) NEW_LINE root . right . left . right = Node ( 8 ) NEW_LINE total = 0 NEW_LINE leafSum ( root ) NEW_LINE print ( total ) NEW_LINE DEDENT