Python Program to Implement Depth First Search Traversal using Post Order

When it is required to implement depth first search using post order traversal, a tree class is created with methods to add element, search for a specific element, and perform post order traversal and so on. An instance of the class is created, and it can be used to access the methods.

Below is the demonstration of the same −


 Live Demo

class Tree_Struct:
   def __init__(self, key=None):
      self.key = key
      self.children = []

   def add_elem(self, node):
   def search_elem(self, key):
      if self.key == key:
         return self
      for child in self.children:
         temp = child.search_elem(key)
         if temp is not None:
            return temp
      return None

   def postorder_traversal(self):
      for child in self.children:
      print(self.key, end=' ')

my_instance = None

print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')

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
         position = my_input[3].strip().lower()
         key = int(position)
         ref_node = None
         if my_instance is not None:
            ref_node = my_instance.search_elem(key)
         if ref_node is None:
            print('No such key exists')

   elif operation == 'dfs':
      print('The post-order traversal is : ', end='')

   elif operation == 'quit':


Menu (this assumes no duplicate keys)
add <data> at root
add <data> below <data>
What operation would you do ? add 5 at root
What operation would you do ? insert 9 below 5
What operation would you do ? insert 2 below 9
What operation would you do ? dfs
The post-order traversal is : 5
What operation would you do ? quit


  • The ‘Tree_struct’ class with required attributes is created.

  • It has an ‘init’ function that is used to create an empty list.

  • It has an ‘add_elem’ method that helps add elements to the tree.

  • Another method named ‘postorder_traversal’ that performs postorder traversal.

  • A method named ‘search_elem’ is defined, that helps search for a specific element.

  • An instance is created and assigned to ‘None’.

  • The user input is taken for the operation that needs to be performed.

  • Depending on the user’ choice, the operation is performed.

  • Relevant output is displayed on the console.

Updated on: 16-Apr-2021


Kickstart Your Career

Get certified by completing the course

Get Started