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.- class Tree:
- def __init__(self, data=None):
- self.key = data
- self.children = []
- def set_root(self, data):
- self.key = data
- def add(self, node):
- self.children.append(node)
- def search(self, key):
- if self.key == key:
- return self
- for child in self.children:
- temp = child.search(key)
- if temp is not None:
- return temp
- return None
- def bfs(self):
- queue = [self]
- while queue:
- node = queue.pop(0)
- print(node.key, end=' ')
- for child in node.children:
- queue.append(child)
- # MAIN PROGRAM
- while True:
- print("\n================= Display Tree Nodes using BFS Traversal =================\n")
- tree = None
- print('Menu (this assumes no duplicate keys)')
- print('add <data> at root')
- print('add <data> below <data>')
- print('bfs')
- print('quit')
- while True:
- do = input('What would you like to do? ').split()
- if not do:
- continue
- operation = do[0].strip().lower()
- if operation == 'add':
- data = int(do[1])
- new_node = Tree(data)
- suboperation = do[2].strip().lower()
- if suboperation == 'at':
- tree = new_node
- elif suboperation == 'below':
- key = int(do[3])
- if tree is None:
- print('Tree is empty. Add a root first.')
- continue
- ref_node = tree.search(key)
- if ref_node is None:
- print('No such key.')
- continue
- ref_node.add(new_node)
- elif operation == 'bfs':
- if tree is None:
- print('Tree is empty.')
- else:
- print('BFS traversal: ', end='')
- tree.bfs()
- print()
- elif operation == 'quit':
- break
- else:
- print('Invalid command.')
- # Try again option
- opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
- if opt == "no":
- print("Exiting program...")
- break
- elif opt != "yes":
- print("Invalid choice. Exiting program...")
- 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