Python program to print all elements of a Binary tree














































Python program to print all elements of a Binary tree



Python program to print all the elements of a binary tree
This program prints the element of each node and then recursively calls itself first on
that node%u2019s left child node and then on right child node, if any exists. For the following
input tree:

1
/
2 3
/
4 5
The output is :

1 2 4 5 3.

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



#Program to print all the elements of a Binary tree
class Node(object):
    #Constructor
    def __init__(self,data):            
        self.data=data
        self.left=None
        self.right=None

#Function to print the all elements 
    def print_elements(self): 
        if(self is None):
            return 0
        print( self.data)
        if self.left:
            self.left.print_elements()
        if self.right:
            self.right.print_elements()

    # main
if __name__ == '__main__':
    #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)
 #   print_elements(root)
    root.print_elements()

Comments