How to Construct and Operate on Trees in Python

In this tutorial, we will learn how to program “How to Construct and Operate on Trees in Python.” The main objective is to understand how tree data structures are built and how different operations can be performed on them. This tutorial will guide you step by step through the process of constructing a tree and implementing common tree operations such as insertion, traversal, and searching. By the end of this tutorial, you will have a solid understanding of how 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, parent=None):
  3.         self.key = data
  4.         self.children = []
  5.         self.parent = parent
  6.  
  7.     def add(self, node):
  8.         self.children.append(node)
  9.  
  10.     def search(self, key):
  11.         if self.key == key:
  12.             return self
  13.         for child in self.children:
  14.             found = child.search(key)
  15.             if found:
  16.                 return found
  17.         return None
  18.  
  19.     def remove(self):
  20.         parent = self.parent
  21.         index = parent.children.index(self)
  22.         parent.children.remove(self)
  23.         for child in reversed(self.children):
  24.             parent.children.insert(index, child)
  25.             child.parent = parent
  26.  
  27.     def bfs_display(self):
  28.         queue = [self]
  29.         while queue:
  30.             current = queue.pop(0)
  31.             print(current.key, end=" ")
  32.             for child in current.children:
  33.                 queue.append(child)
  34.  
  35.  
  36. # MAIN PROGRAM
  37. while True:
  38.     print("\n================= Construct and Operate on Trees =================\n")
  39.  
  40.     tree = None
  41.  
  42.     print("Menu (this assumes no duplicate keys)")
  43.     print("add <data> at root")
  44.     print("add <data> below <data>")
  45.     print("remove <data>")
  46.     print("display")
  47.     print("quit")
  48.  
  49.     while True:
  50.         do = input("\nWhat would you like to do? ").split()
  51.         if not do:
  52.             continue
  53.  
  54.         operation = do[0].lower()
  55.  
  56.         if operation == "add":
  57.             data = int(do[1])
  58.             new_node = Tree(data)
  59.  
  60.             if do[2] == "at" and do[3] == "root":
  61.                 if tree is None:
  62.                     tree = new_node
  63.                 else:
  64.                     print("Root already exists.")
  65.  
  66.             elif do[2] == "below":
  67.                 key = int(do[3])
  68.                 ref_node = tree.search(key) if tree else None
  69.                 if ref_node is None:
  70.                     print("No such key.")
  71.                 else:
  72.                     new_node.parent = ref_node
  73.                     ref_node.add(new_node)
  74.  
  75.         elif operation == "remove":
  76.             if tree is None:
  77.                 print("Tree is empty.")
  78.                 continue
  79.  
  80.             key = int(do[1])
  81.             node = tree.search(key)
  82.  
  83.             if node is None:
  84.                 print("No such key.")
  85.             elif node == tree:
  86.                 if not tree.children:
  87.                     tree = None
  88.                 else:
  89.                     new_root = tree.children[0]
  90.                     new_root.parent = None
  91.                     tree.children.remove(new_root)
  92.                     new_root.children.extend(tree.children)
  93.                     for c in new_root.children:
  94.                         c.parent = new_root
  95.                     tree = new_root
  96.             else:
  97.                 node.remove()
  98.  
  99.         elif operation == "display":
  100.             if tree:
  101.                 print("BFS traversal display:", end=" ")
  102.                 tree.bfs_display()
  103.                 print()
  104.             else:
  105.                 print("Tree is empty.")
  106.  
  107.         elif operation == "quit":
  108.             break
  109.  
  110.         else:
  111.             print("Invalid command.")
  112.  
  113.     # Try again option
  114.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  115.     if opt == "no":
  116.         print("Exiting program...")
  117.         break
  118.     elif opt != "yes":
  119.         print("Invalid choice. Exiting program...")
  120.         break

This program demonstrates how to construct and operate on a tree data structure in Python using a simple, object-oriented approach. Each node in the tree is represented by the `Tree` class, which stores a key, a reference to its parent, and a list of its children. The program allows users to add nodes either as the root or below an existing node, search for nodes recursively, remove nodes while preserving their children by reattaching them to the parent, and display the tree using a breadth-first search (BFS) traversal. Through a menu-driven interface, users can interactively build, modify, and visualize the tree, making this program a clear and practical example of basic tree construction and operations.

Output:

There you have it we successfully created How to Construct and Operate on Trees 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