Level order traversal of a binary tree in python.

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

If you want to learn data structures in python you can read the below books.

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:

                return

        node = queue[0]

        queue.pop(0)

        if node.left:

                queue.append(node.left)

        if node.right:

                queue.append(node.right)

        print node.data

        level_order(queue)

queue = list()

root = Node(1)

queue.append(root)

root.left = Node(2)

root.right = Node(3)

root.left.left = Node(4)

root.left.right = Node(5)

level__order(queue)

# 1 2 3 4 5 

Length of Longest Increasing Subsequence (LIS) in python [Dynamic Programming]

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.

Algorithms: Mirror a Binary tree using python

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

Please share and subscribe.


Gaurav Yadav

Gaurav is cloud infrastructure engineer and a full stack web developer and blogger. Sportsperson by heart and loves football. Scale is something he loves to work for and always keen to learn new tech. Experienced with CI/CD, distributed cloud infrastructure, build systems and lot of SRE Stuff.

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.