Breadth first search tree in python

 Breadth-first search tree in python



Breadth-first search (BFS) is an algorithm for traversing a tree or graph data structure. It starts at the tree root (or some arbitrary node of a graph) and explores the neighbor nodes first, before moving to the next level neighbors.

Here is an example of how you might implement breadth-first search (BFS) on a tree in Python:

class Node:
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right

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

root = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6), Node(7)))
breadth_first_search(root)

In this example, the breadth_first_search function takes a tree root node as input and performs a breadth-first search on the tree. It uses a queue to store the nodes that have been visited but not yet processed, and it adds the left and right children of each node to the queue as it processes them. The function prints the value of each node as it is visited.

Post a Comment

0 Comments