Credit: FreeCodecamp

Introduction:

In binary trees, exploring their structure and nodes in a systematic manner is crucial for various operations and analyses. One such traversal method is the level order traversal, which traverses the tree level by level, starting from the root node. Through this tutorial, we’ll delve into the intricacies of level order traversal and learn how to implement it efficiently in Python.

Problem Statement:

Given a binary tree, our objective is to traverse its nodes in level order and print them out, starting from the root node and proceeding level by level.

Understanding the Approach:

Level order traversal involves systematically traversing the tree, starting from the root node and visiting nodes at each level from left to right. We utilize a queue data structure to keep track of nodes at each level, ensuring that nodes are processed in a breadth-first manner.

Algorithm Overview:

  1. Create an empty queue to store nodes.
  2. Enqueue the root node into the queue.
  3. While the queue is not empty:
    • Dequeue a node from the front of the queue.
    • Print the value of the dequeued node.
    • Enqueue the left child (if any) of the dequeued node.
    • Enqueue the right child (if any) of the dequeued node.
  4. Repeat steps 3 until the queue becomes empty.

Implementation in Python:

from collections import deque

class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = None
        self.right = None

def level_order_traversal(root):
    if not root:
        return []

    result = []
    queue = deque()
    queue.append(root)

    while queue:
        node = queue.popleft()
        result.append(node.val)

        if node.left:
            queue.append(node.left)
        if node.right:
            queue.append(node.right)

    return result

def build_tree(nodes):
    if not nodes:
        return None

    root = TreeNode(int(nodes[0]))
    queue = deque()
    queue.append(root)
    i = 1

    while queue:
        node = queue.popleft()

        if i < len(nodes) and nodes[i] != "-1":
            node.left = TreeNode(int(nodes[i]))
            queue.append(node.left)
        i += 1

        if i < len(nodes) and nodes[i] != "-1":
            node.right = TreeNode(int(nodes[i]))
            queue.append(node.right)
        i += 1

    return root

# Main function
if __name__ == "__main__":
    T = int(input().strip())  # Read the number of test cases

    for _ in range(T):
        nodes = input().strip().split()  # Read the level order traversal of the tree
        root = build_tree(nodes)  # Build the binary tree
        result = level_order_traversal(root)  # Perform level order traversal
        print(" ".join(map(str, result)))  # Print the result

Conclusion: Level order traversal offers a systematic approach to explore the nodes of a binary tree in a breadth-first manner. By implementing this traversal technique, you gain insights into the hierarchical structure of the tree and efficiently process its nodes. Armed with this knowledge, you’re better equipped to navigate and analyze binary trees with confidence. Happy traversing!

By

Leave a Reply

Discover more from Geeky Codes

Subscribe now to keep reading and get access to the full archive.

Continue reading