Python

Level Order Tree Traversal in Python

Level order tree traversal is a technique to visit all the nodes of a binary tree in a way that nodes at the same level are visited before nodes at a lower level. It is also known as breadth-first search or BFS.

Algorithm

The algorithm for level order tree traversal can be summarized as follows:

  • Create an empty queue and enqueue the root node of the tree.
  • While the queue is not empty, do the following steps:
    • Dequeue a node from the queue and print its value.
    • If the node has a left child, enqueue it to the queue.
    • If the node has a right child, enqueue it to the queue.

Python Code

# Define a class for the nodes of the binary tree
class Node:
  def __init__(self, data):
    self.data = data
    self.left = None
    self.right = None

# Define a function to perform level order traversal
def level_order_traversal(root):
  # Create an empty queue
  queue = []
  # Enqueue the root node
  queue.append(root)
  # Loop until the queue is empty
  while queue:
    # Dequeue a node from the queue
    node = queue.pop(0)
    # Print its value
    print(node.data, end=" ")
    # Enqueue its left child if exists
    if node.left:
      queue.append(node.left)
    # Enqueue its right child if exists
    if node.right:
      queue.append(node.right)

# Create a sample binary tree
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)

# Call the function to perform level order traversal
level_order_traversal(root)

Output

The output of the above code is:

1 2 3 4 5 6 7 

Explanation

The above code creates a binary tree with the following structure:

Related Post
     1
   /   \
  2     3
 / \   / \
4   5 6   7

The level order traversal of this tree is:

1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7

The code uses a queue to store the nodes that need to be visited next. It starts with enqueuing the root node (1) and then dequeues it and prints its value. Then it enqueues its left child (2) and right child (3) to the queue. The queue now contains [2, 3].

The next iteration dequeues the node (2) and prints its value. Then it enqueues its left child (4) and right child (5) to the queue. The queue now contains [3, 4, 5].

The next iteration dequeues the node (3) and prints its value. Then it enqueues its left child (6) and right child (7) to the queue. The queue now contains [4, 5, 6, 7].

The next iterations dequeue and print the remaining nodes in the queue until it becomes empty.

Aditya Kumar

Share
Tags: Python Python Data Structure

Recent Posts

  • Programming

Mastering Print Formatting in Python: A Comprehensive Guide

In Python, the print() function is a fundamental tool for displaying output. While printing simple…

8 months ago
  • Programming

Global Variables in Python: Understanding Usage and Best Practices

Python is a versatile programming language known for its simplicity and flexibility. When working on…

8 months ago
  • Programming

Secure Your Documents: Encrypting PDF Files Using Python

PDF (Portable Document Format) files are commonly used for sharing documents due to their consistent…

8 months ago
  • Programming

Creating and Modifying PDF Files in Python: A Comprehensive Guide with Code Examples

PDF (Portable Document Format) files are widely used for document exchange due to their consistent…

8 months ago
  • Programming

Boosting Python Performance with Cython: Optimizing Prime Number Detection

Python is a high-level programming language known for its simplicity and ease of use. However,…

8 months ago
  • Programming

Using OOP, Iterator, Generator, and Closure in Python to implement common design patterns

Object-Oriented Programming (OOP), iterators, generators, and closures are powerful concepts in Python that can be…

8 months ago

This website uses cookies.