Level order traversal of a binary tree in python.

Level order traversal of a binary tree in python.
5 (100%) 4 votes

Binary tree are the tree where one node can have only two child and cannot have more than two.

Level order traversal of a binary tree.

Level order traversal means that we visit the nodes level by level. Like for below tree the level order traversal will be Level order traversal of a binary tree.

Its Level order traversal will be

1 2 3 4 5

Here is the code for doing that.

class Node:

        def __init__(self,data):

                self.left = None

                self.right = None

                self.data = data

def level_order(queue):

        if len(queue) == 0:


        node = queue[0]


        if node.left:


        if node.right:


        print node.data


queue = list()

root = Node(1)


root.left = Node(2)

root.right = Node(3)

root.left.left = Node(4)

root.left.right = Node(5)


# 1 2 3 4 5 

What we did here:

We make use of queues to do the level order traversal. What we did is we visit a node and put its left and right child in the queue and delete the current node. In this way we visit the tree in level order.

Wanna read more about Algorithms and Data structures visit below link.
Algorithms and Data Structures.

Please share and subscribe.

Gaurav Yadav

Gaurav is a Full Stack Web Developer and Blogger. Sportsperson by heart and loves football. He has experience with various frameworks in php, python and javascript. Loves to explore new frameworks and evolve with the trending technology.

Leave a Reply

Your email address will not be published. Required fields are marked *