Program to check whether one tree is subtree of other or not in Python

Suppose we have two binary trees. We have to check whether the second tree is a subtree of the first one or not. A subtree means that there exists a node in the main tree such that the subtree rooted at that node has the same structure and node values as the given target tree.

So, if the input is like ?

Main Tree: 6 4 10 3 5 Target Tree: 4 3 5 Match Found!

then the output will be True because the target tree matches the subtree rooted at node 4 in the main tree.

Algorithm

To solve this, we will follow these steps ?

  • Define a function solve() that takes root and target parameters

  • If both root and target are null, return True (both trees are empty)

  • If either root or target is null (but not both), return False

  • If the value of root matches the value of target, check if both subtrees match recursively

  • Otherwise, recursively search in the left and right subtrees of the main tree

Implementation

class TreeNode:
    def __init__(self, data, left=None, right=None):
        self.val = data
        self.left = left
        self.right = right

class Solution:
    def solve(self, root, target):
        # Both trees are empty
        if root is None and target is None:
            return True
        
        # One tree is empty, the other is not
        if root is None or target is None:
            return False
        
        # Current nodes match, check if entire subtrees match
        if root.val == target.val:
            return (self.solve(root.left, target.left) and 
                   self.solve(root.right, target.right))
        else:
            # Search in left or right subtree of main tree
            return (self.solve(root.left, target) or 
                   self.solve(root.right, target))

# Create the main tree
ob = Solution()
root1 = TreeNode(6)
root1.left = TreeNode(4)
root1.right = TreeNode(10)
root1.left.left = TreeNode(3)
root1.left.right = TreeNode(5)

# Create the target tree
root2 = TreeNode(4)
root2.left = TreeNode(3)
root2.right = TreeNode(5)

# Check if root2 is a subtree of root1
result = ob.solve(root1, root2)
print(result)

The output of the above code is ?

True

How It Works

The algorithm works in two phases:

  • Search Phase: When node values don't match, we recursively search in left and right subtrees of the main tree

  • Match Phase: When node values match, we check if the entire subtree structure matches by comparing left and right children recursively

Time and Space Complexity

  • Time Complexity: O(m × n) where m is the number of nodes in the main tree and n is the number of nodes in the target tree

  • Space Complexity: O(h) where h is the height of the main tree due to recursion stack

Conclusion

This recursive solution efficiently checks if one binary tree is a subtree of another by combining tree traversal with structural comparison. The algorithm handles edge cases like empty trees and provides a clean, readable implementation.

Updated on: 2026-03-25T11:40:01+05:30

447 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements