← Back to Codes

2026-06-09 16:36:42

Subtree of Another Tree in Python and Java | LeetCode #572

Learn how to solve Subtree of Another Tree in Python and Java with beginner-friendly explanation, step-by-step dry run, custom examples, and time complexity.

Subtree of Another Tree in Python and Java

In this tutorial, we will learn LeetCode #572: Subtree of Another Tree in very simple language. We will understand the idea step by step, see custom examples, and write complete code in Python and Java.

What Is the Subtree of Another Tree Problem?

This problem asks us to solve a common coding interview task using the given input. The goal is to return the correct result without using a slow brute force method.

For this problem, we will use recursive comparison because it gives a clean and optimized solution.

Example input:
root = [3,4,5,1,2], subRoot = [4,1,2]

Expected result:
Output: true

Explanation:
subRoot exists inside root.

Beginner-Friendly Idea

The main idea is to avoid trying every possible answer blindly. Instead, we keep useful information while reading the input and use that information to make the next decision.

At each step, ask: “What do I already know, and how does the current value change my answer?”

Using our example:
root = [3,4,5,1,2], subRoot = [4,1,2]

Approach:
recursive comparison

We update variables step by step until we reach:
Output: true

Why Do We Use This Approach?

A direct brute force solution is usually easier to think about, but it can become slow when the input is large. The optimized approach keeps only the important state and avoids repeated work.

That is why recursive comparison is useful for this problem.

Step-by-Step Explanation

Let us dry run the algorithm using a custom example.

Step 1
Use this custom example.

root = [3,4,5,1,2], subRoot = [4,1,2]

We will solve it using recursive comparison.

Step 2
Look at the first important value from the example and create the variables needed by the algorithm.

current_state = based on the first value
answer = not finished yet

Step 3
Move to the next useful value and update the state.

The algorithm compares the new value with the old state.
If the new value improves the answer, we update the answer.

Step 4
Continue this process until all useful values are processed.

After processing the example, we get:

Output: true

Why?
subRoot exists inside root.

Important Code Logic

The most important part is updating the algorithm state after reading each useful value. This is where the answer becomes better step by step.

Think like this:

old_state = what we knew before
current_value = value we are checking now
new_state = updated result after using current_value

For our example, the final state gives:
Output: true

Example 1

Input:
root = [3,4,5,1,2], subRoot = [4,1,2]

Output:
Output: true

Explanation:
subRoot exists inside root.

Example 2

Input:
root = [3,4,5,1,2], subRoot = [4,1,2]

Output:
true

Explanation:
The subtree appears inside the main tree.

Python Code

Here is the complete Python solution for LeetCode #572.

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


class SubtreeChecker:
    def is_subtree(self, root, sub_root):
        if not sub_root:
            return True
        if not root:
            return False

        return self.same_tree(root, sub_root) or self.is_subtree(root.left, sub_root) or self.is_subtree(root.right, sub_root)

    def same_tree(self, first, second):
        if not first and not second:
            return True
        if not first or not second:
            return False
        return first.val == second.val and self.same_tree(first.left, second.left) and self.same_tree(first.right, second.right)


root = TreeNode(8, TreeNode(4, TreeNode(2), TreeNode(6)), TreeNode(10))
sub_root = TreeNode(4, TreeNode(2), TreeNode(6))
checker = SubtreeChecker()
print(checker.is_subtree(root, sub_root))  # Output: True

Java Code

Here is the complete Java solution for LeetCode #572.

class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int val) { this.val = val; }
}

class SubtreeChecker {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (subRoot == null) return true;
        if (root == null) return false;

        return sameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

    private boolean sameTree(TreeNode first, TreeNode second) {
        if (first == null && second == null) return true;
        if (first == null || second == null) return false;
        return first.val == second.val && sameTree(first.left, second.left) && sameTree(first.right, second.right);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(8);
        root.left = new TreeNode(4);
        root.right = new TreeNode(10);
        root.left.left = new TreeNode(2);
        root.left.right = new TreeNode(6);

        TreeNode subRoot = new TreeNode(4);
        subRoot.left = new TreeNode(2);
        subRoot.right = new TreeNode(6);

        SubtreeChecker checker = new SubtreeChecker();
        System.out.println(checker.isSubtree(root, subRoot)); // true
    }
}

Time and Space Complexity

Time Complexity: O(n)

The time complexity depends on how many values the algorithm needs to process and whether it uses sorting, binary search, heap, or traversal.

Space Complexity: O(n)

The extra space is used for the variables or data structures needed by the optimized approach.

Final Summary

LeetCode #572: Subtree of Another Tree becomes easier when we break it into small steps. First understand what the problem asks, then track the important state, dry run with an example, and finally write the code.