Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Display the Nodes of a Tree using BFS Traversal
When it is required to display the nodes of a tree using the breadth first search traversal, a class is created, and it contains methods to set the root node, add elements to the tree, search for a specific element, perform BFS (breadth first search) and so on. An instance of the class can be created to access and use these methods.
Below is a demonstration of the same ?
Tree Structure Class
First, let's create a simplified version that demonstrates the core BFS concept ?
class Tree_struct:
def __init__(self, data=None):
self.key = data
self.children = []
def add_child(self, child_node):
self.children.append(child_node)
def bfs_traversal(self):
if self.key is None:
return
queue = [self]
result = []
while queue:
current = queue.pop(0)
result.append(current.key)
for child in current.children:
queue.append(child)
return result
# Create a sample tree
root = Tree_struct(1)
child1 = Tree_struct(2)
child2 = Tree_struct(3)
child3 = Tree_struct(4)
child4 = Tree_struct(5)
root.add_child(child1)
root.add_child(child2)
child1.add_child(child3)
child1.add_child(child4)
# Perform BFS traversal
print("BFS Traversal:", root.bfs_traversal())
BFS Traversal: [1, 2, 3, 4, 5]
Complete Interactive Version
Here's the full interactive program with proper formatting ?
class Tree_struct:
def __init__(self, data=None):
self.key = data
self.children = []
def set_root(self, data):
self.key = data
def add_node(self, node):
self.children.append(node)
def search_node(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search_node(key)
if temp is not None:
return temp
return None
def bfs_operation(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')
# Create tree instance
my_instance = None
print('Menu (assume no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('bfs')
print('quit')
while True:
my_input = input('What operation would you do ? ').split()
operation = my_input[0].strip().lower()
if operation == 'add':
data = int(my_input[1])
new_node = Tree_struct(data)
suboperation = my_input[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
elif suboperation == 'below':
position = my_input[3].strip().lower()
key = int(position)
ref_node = None
if my_instance is not None:
ref_node = my_instance.search_node(key)
if ref_node is None:
print('No such key')
continue
ref_node.add_node(new_node)
elif operation == 'bfs':
if my_instance is None:
print('The tree is empty')
else:
print('Breadth First Search traversal is : ', end='')
my_instance.bfs_operation()
print()
elif operation == 'quit':
break
How BFS Works
Breadth First Search (BFS) traverses a tree level by level using a queue data structure ?
Key Features
The
Tree_structclass represents a general tree (not binary) where each node can have multiple childrenThe
bfs_operationmethod uses a queue to traverse nodes level by levelThe
search_nodemethod recursively finds a node with a specific keyThe interactive menu allows users to build trees and perform BFS traversal dynamically
Sample Output
Menu (assume no duplicate keys) add <data> at root add <data> below <data> bfs quit What operation would you do ? add 6 at root What operation would you do ? add 4 below 6 What operation would you do ? add 9 below 4 What operation would you do ? bfs Breadth First Search traversal is : 6 4 9 What operation would you do ? quit
Conclusion
BFS traversal visits tree nodes level by level using a queue data structure. This approach ensures all nodes at depth d are visited before any nodes at depth d+1, making it useful for finding shortest paths and level-order processing.
