Google News
logo
Python Program to Display Tree Nodes using BFS Traversal
In the following example of a Python program that displays the nodes of a binary tree using breadth-first search (BFS) traversal :
Program :
class Node:
    def __init__(self, value):
        self.value = value
        self.left = None
        self.right = None

class BinaryTree:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root is None:
            self.root = Node(value)
        else:
            self._insert(value, self.root)

    def _insert(self, value, node):
        if value < node.value:
            if node.left is None:
                node.left = Node(value)
            else:
                self._insert(value, node.left)
        else:
            if node.right is None:
                node.right = Node(value)
            else:
                self._insert(value, node.right)

    def bfs_traversal(self):
        if self.root is None:
            return
        queue = [self.root]
        while queue:
            node = queue.pop(0)
            print(node.value)
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)

# Example usage
tree = BinaryTree()
tree.insert(5)
tree.insert(3)
tree.insert(7)
tree.insert(1)
tree.insert(4)
tree.insert(6)
tree.insert(8)

print("BFS Traversal:")
tree.bfs_traversal()
Output :
BFS Traversal:
5
3
7
1
4
6
8
In the above example, the `Node` class and `BinaryTree` class are the same as in the previous examples. The new method `bfs_traversal()` performs a BFS traversal of the binary tree.

It initializes a queue with the root node and repeatedly dequeues nodes from the queue, prints their value, and enqueues their left and right children (if they exist) onto the queue.

The example usage at the bottom of the program constructs a binary search tree with some example values, and then calls `bfs_traversal()` to display the nodes of the tree using BFS traversal.