Python program to find the sum of all leaf nodes of a binary tree














































Python program to find the sum of all leaf nodes of a binary tree



Program Description:
Python program to find the sum of all leaf nodes of a binary tree
This program first checks each node of the tree to verify if it is a leaf node or not and then when it finds a leaf node it adds the data value of that leaf node to the variable sum and prints the sum . The following is the binary tree in that is the input for the program:
					
					     1
			                   /  \  
					  2    3
				        / \
				       4   5
The output is the sum of the leaf nodes as follows:
4  + 5 + 3= 12

The time complexity of this program is O(n) where n is the number of nodes  in the 
tree as it has to check each node of the tree.

Program:
#class to create a node of a binary tree with the data value passed as parameter
class Node(object):
    #Constructor
    def __init__(self, data):            
        self.data=data
        self.left=None
        self.right=None

#Function to print the leaf nodes and sum of their values
def sum_of_leaves(self): 
    global sum      
    if(self is None):
        return 0
    if((self.left is None) and (self.right is None)):
        print(" {} is a  leaf node".format(self.data))
        sum +=self.data
    sum_of_leaves(self.left)
    sum_of_leaves(self.right)
#Create the binary tree
root=Node(1)
root.left=Node(2)
root.right=Node(3)
root.left.left=Node(4)
root.left.right=Node(5)
sum_of_leaves(root)
print("The total of leaf nodes is {}".format(sum))

Comments