How to Implement DFS Traversal with Recursion in Python

In this tutorial, we will learn how to program “How to Implement DFS Traversal with Recursion in Python.” The main objective is to understand how to implement DFS traversal using recursion. This tutorial will guide you step by step through the process of implementing DFS traversal. By the end of this tutorial, you will have a solid understanding of how DFS traversal works 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 implementing DFS Traversal with Recursion. So, let’s dive into the coding process and start implementing the solution to gain a deeper understanding of graph traversal algorithms 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 BinaryTree:
  2.     def __init__(self, key=None):
  3.         self.key = key
  4.         self.left = None
  5.         self.right = None
  6.  
  7.     def set_root(self, key):
  8.         self.key = key
  9.  
  10.     def insert_left(self, new_node):
  11.         self.left = new_node
  12.  
  13.     def insert_right(self, new_node):
  14.         self.right = new_node
  15.  
  16.     def search(self, key):
  17.         if self.key == key:
  18.             return self
  19.  
  20.         if self.left is not None:
  21.             temp = self.left.search(key)
  22.             if temp is not None:
  23.                 return temp
  24.  
  25.         if self.right is not None:
  26.             temp = self.right.search(key)
  27.             return temp
  28.  
  29.         return None
  30.  
  31.     def depth_first(self):
  32.         print("entering {}...".format(self.key))
  33.  
  34.         if self.left is not None:
  35.             self.left.depth_first()
  36.  
  37.         print("at {}...".format(self.key))
  38.  
  39.         if self.right is not None:
  40.             self.right.depth_first()
  41.  
  42.         print("leaving {}...".format(self.key))
  43.  
  44.  
  45. # MAIN PROGRAM
  46. while True:
  47.  
  48.     print("\n================= Implement DFS Traversal with Recursion =================\n")
  49.  
  50.     btree = None
  51.  
  52.     print("Menu (this assumes no duplicate keys)")
  53.     print("insert <data> at root")
  54.     print("insert <data> left of <data>")
  55.     print("insert <data> right of <data>")
  56.     print("dfs")
  57.     print("quit")
  58.  
  59.     while True:
  60.  
  61.         do = input("\nWhat would you like to do? ").split()
  62.  
  63.         if len(do) == 0:
  64.             continue
  65.  
  66.         operation = do[0].lower()
  67.  
  68.         if operation == "insert":
  69.  
  70.             data = int(do[1])
  71.             new_node = BinaryTree(data)
  72.  
  73.             suboperation = do[2].lower()
  74.  
  75.             if suboperation == "at":
  76.                 btree = new_node
  77.  
  78.             else:
  79.                 key = int(do[4])
  80.  
  81.                 ref_node = None
  82.                 if btree is not None:
  83.                     ref_node = btree.search(key)
  84.  
  85.                 if ref_node is None:
  86.                     print("No such key.")
  87.                     continue
  88.  
  89.                 if suboperation == "left":
  90.                     ref_node.insert_left(new_node)
  91.  
  92.                 elif suboperation == "right":
  93.                     ref_node.insert_right(new_node)
  94.  
  95.         elif operation == "dfs":
  96.  
  97.             print("\nDepth-first search traversal:")
  98.  
  99.             if btree is not None:
  100.                 btree.depth_first()
  101.             else:
  102.                 print("Tree is empty.")
  103.  
  104.             print()
  105.  
  106.         elif operation == "quit":
  107.             break
  108.  
  109.         else:
  110.             print("Invalid command.")
  111.  
  112.     # Try Again Option
  113.     opt = input("\nDo you want to try again? (yes/no): ").strip().lower()
  114.  
  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 implement a Depth-First Search (DFS) traversal on a binary tree using recursion. It defines a `BinaryTree` class where each node has a key and pointers to left and right children. Users can build a binary tree interactively through a menu by inserting a node at the root or attaching nodes as the left or right child of an existing node. The `depth_first` method performs a DFS traversal, printing messages as it "enters" a node, visits it, and "leaves" it, giving a clear visualization of the recursive traversal order. The program also allows searching for nodes by key to attach new nodes correctly and provides an option to quit or repeat the process. It ensures the tree is traversed recursively and outputs the DFS path step by step.

Output:

There you have it we successfully created How to Implement DFS Traversal with Recursion 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