How to Display Tree Nodes using BFS Traversal in Python

In this tutorial, we will learn how to program “How to Display Tree Nodes Using BFS Traversal in Python.” The main objective is to display tree nodes using BFS traversal. This tutorial will guide you step by step through the process of traversing and displaying tree nodes. By the end, you will have a solid understanding of how binary trees work in Python, helping you strengthen your problem-solving abilities and improve your overall coding skills in data structure implementation.

This topic is straightforward and easy to understand. By simply following the instructions provided, you will be able to complete it with ease. The program will guide you step by step through the process of constructing a tree and performing various operations on it, such as insertion, traversal, and manipulation of nodes. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of tree data structures in Python!

Getting Started:

First you will have to download & install the Python IDLE's, here's the link for the Integrated Development And Learning Environment for Python https://www.python.org/downloads/.

Creating Main Function

This is the main function of the application. The following code will display a simple GUI in terminal console that will display program. To do this, simply copy and paste these blocks of code into the IDLE text editor.
  1. class Tree:
  2.     def __init__(self, data=None):
  3.         self.key = data
  4.         self.children = []
  5.  
  6.     def set_root(self, data):
  7.         self.key = data
  8.  
  9.     def add(self, node):
  10.         self.children.append(node)
  11.  
  12.     def search(self, key):
  13.         if self.key == key:
  14.             return self
  15.         for child in self.children:
  16.             temp = child.search(key)
  17.             if temp is not None:
  18.                 return temp
  19.         return None
  20.  
  21.     def bfs(self):
  22.         queue = [self]
  23.         while queue:
  24.             node = queue.pop(0)
  25.             print(node.key, end=' ')
  26.             for child in node.children:
  27.                 queue.append(child)
  28.  
  29.  
  30. # MAIN PROGRAM
  31. while True:
  32.     print("\n================= Display Tree Nodes using BFS Traversal =================\n")
  33.  
  34.     tree = None
  35.     print('Menu (this assumes no duplicate keys)')
  36.     print('add <data> at root')
  37.     print('add <data> below <data>')
  38.     print('bfs')
  39.     print('quit')
  40.  
  41.     while True:
  42.         do = input('What would you like to do? ').split()
  43.         if not do:
  44.             continue
  45.  
  46.         operation = do[0].strip().lower()
  47.  
  48.         if operation == 'add':
  49.             data = int(do[1])
  50.             new_node = Tree(data)
  51.             suboperation = do[2].strip().lower()
  52.             if suboperation == 'at':
  53.                 tree = new_node
  54.             elif suboperation == 'below':
  55.                 key = int(do[3])
  56.                 if tree is None:
  57.                     print('Tree is empty. Add a root first.')
  58.                     continue
  59.                 ref_node = tree.search(key)
  60.                 if ref_node is None:
  61.                     print('No such key.')
  62.                     continue
  63.                 ref_node.add(new_node)
  64.  
  65.         elif operation == 'bfs':
  66.             if tree is None:
  67.                 print('Tree is empty.')
  68.             else:
  69.                 print('BFS traversal: ', end='')
  70.                 tree.bfs()
  71.                 print()
  72.  
  73.         elif operation == 'quit':
  74.             break
  75.  
  76.         else:
  77.             print('Invalid command.')
  78.  
  79.     # Try again option
  80.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  81.     if opt == "no":
  82.         print("Exiting program...")
  83.         break
  84.     elif opt != "yes":
  85.         print("Invalid choice. Exiting program...")
  86.         break

This program provides a simple interactive implementation of a general tree and allows the user to explore BFS (Breadth-First Search) traversal. The `Tree` class defines each node with a key and a list of children, supporting operations such as setting the root, adding child nodes, and searching for a specific key recursively. The BFS method traverses the tree level by level, printing the keys of all nodes. In the program, users can build a tree interactively by adding a root node or adding nodes below existing nodes. After constructing the tree, users can display its nodes in BFS order, which prints nodes from top to bottom, left to right, giving a clear view of the tree structure. The menu-driven interface also allows quitting the program or restarting to build a new tree, making it a practical exercise in tree construction and traversal.

Output:

There you have it we successfully created How to Display Tree Nodes using BFS Traversal in Python. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!

More Tutorials for Python Language

Python Tutorials