Python Program for Depth First Binary Tree Search using Recursion

Depth First Search (DFS) is a tree traversal algorithm that explores nodes by going as deep as possible before backtracking. In binary trees, DFS can be implemented recursively by visiting the current node, then traversing the left subtree, and finally the right subtree.

Binary Tree Class Structure

First, let's define a binary tree class with methods for insertion and DFS traversal ?

class BinaryTree_struct:
    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None

    def set_root(self, key):
        self.key = key

    def insert_at_left(self, new_node):
        self.left = new_node

    def insert_at_right(self, new_node):
        self.right = new_node

    def search_elem(self, key):
        if self.key == key:
            return self
        if self.left is not None:
            temp = self.left.search_elem(key)
            if temp is not None:
                return temp
        if self.right is not None:
            temp = self.right.search_elem(key)
            return temp
        return None

    def depth_first_search(self):
        print('entering {}...'.format(self.key))
        if self.left is not None:
            self.left.depth_first_search()
        print('at {}...'.format(self.key))
        if self.right is not None:
            self.right.depth_first_search()
        print('leaving {}...'.format(self.key))

Simple DFS Example

Here's a simpler example showing DFS traversal on a predefined tree ?

class BinaryTree:
    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None

    def depth_first_search(self):
        print('Visiting node:', self.key)
        if self.left is not None:
            self.left.depth_first_search()
        if self.right is not None:
            self.right.depth_first_search()

# Create a binary tree
root = BinaryTree(1)
root.left = BinaryTree(2)
root.right = BinaryTree(3)
root.left.left = BinaryTree(4)
root.left.right = BinaryTree(5)

print("Depth First Search Traversal:")
root.depth_first_search()
Depth First Search Traversal:
Visiting node: 1
Visiting node: 2
Visiting node: 4
Visiting node: 5
Visiting node: 3

Interactive Tree Builder

The following example provides an interactive menu to build and traverse a binary tree ?

class BinaryTree_struct:
    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None

    def insert_at_left(self, new_node):
        self.left = new_node

    def insert_at_right(self, new_node):
        self.right = new_node

    def search_elem(self, key):
        if self.key == key:
            return self
        if self.left is not None:
            temp = self.left.search_elem(key)
            if temp is not None:
                return temp
        if self.right is not None:
            temp = self.right.search_elem(key)
            return temp
        return None

    def depth_first_search(self):
        print('entering {}...'.format(self.key))
        if self.left is not None:
            self.left.depth_first_search()
        print('at {}...'.format(self.key))
        if self.right is not None:
            self.right.depth_first_search()
        print('leaving {}...'.format(self.key))

btree_instance = None

print('Menu (no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('dfs')
print('quit')

while True:
    my_input = input('What would you like to do? ').split()
    
    op = my_input[0].strip().lower()
    if op == 'insert':
        data = int(my_input[1])
        new_node = BinaryTree_struct(data)
        sub_op = my_input[2].strip().lower()
        if sub_op == 'at':
            btree_instance = new_node
        else:
            position = my_input[4].strip().lower()
            key = int(position)
            ref_node = None
            if btree_instance is not None:
                ref_node = btree_instance.search_elem(key)
            if ref_node is None:
                print('No such key.')
                continue
            if sub_op == 'left':
                ref_node.insert_at_left(new_node)
            elif sub_op == 'right':
                ref_node.insert_at_right(new_node)
    elif op == 'dfs':
        print('depth-first search traversal:')
        if btree_instance is not None:
            btree_instance.depth_first_search()
        print()
    elif op == 'quit':
        break

How DFS Works

The recursive DFS algorithm follows these steps:

  1. Visit current node: Process the current node's data
  2. Traverse left subtree: Recursively call DFS on the left child
  3. Traverse right subtree: Recursively call DFS on the right child

This creates a pre-order traversal pattern (root ? left ? right). The recursion naturally handles the backtracking when leaf nodes are reached.

Key Features

  • Recursive implementation: Uses function call stack for backtracking
  • Complete exploration: Visits all nodes in the tree
  • Memory efficient: No additional data structures needed
  • Depth-first order: Explores deepest paths before moving to siblings

Conclusion

Depth First Search using recursion is an elegant way to traverse binary trees. The recursive nature automatically handles the backtracking, making the code simple and intuitive to understand.

Updated on: 2026-03-25T19:09:53+05:30

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements