Tensorum
LeetCode 572 · DFS Basics

Subtree of Another Tree

LeetCode 572 · Easy · solution, intuition & step-by-step walkthrough

isSubtree = sameTree(root, sub) or recurse into children.

EasyTreeDepth-First SearchString MatchingBinary TreeHash Function
66 msruntime · beats 6%
55.6 MBmemory · beats 100%
1approach
3accepted runs · last 25 Jun 2024

This is how I solved Subtree of Another Tree (LeetCode 572), an easy problem from the DFS Basics pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.

Intuition

For every node of the main tree, ask: is the tree rooted here the same as subRoot? Reuse the same-tree check.

Approach

  1. 1

    Empty root → False.

  2. 2

    If sameTree(root, subRoot), done.

  3. 3

    Otherwise try root.left and root.right.

How I solved it

Same-tree at every nodePythonO(m·n) time
class Solution:
    def isSameTree(self, p, q):
        if p is None and q is None:
            return True
        if p is None or q is None:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

    def isSubtree(self, root, subRoot):
        if root is None:
            return False
        if self.isSameTree(root, subRoot):
            return True
        return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
Loading the step-through…

Subtree of Another Tree — FAQ

What is the intuition behind Subtree of Another Tree?

For every node of the main tree, ask: is the tree rooted here the same as subRoot? Reuse the same-tree check.

How do you solve Subtree of Another Tree (LeetCode 572)?

1. Empty root → False. 2. If sameTree(root, subRoot), done. 3. Otherwise try root.left and root.right.

What is the time and space complexity of Subtree of Another Tree?

Time: O(m · n). Space: O(h). (Accepted approach: Same-tree at every node.)

What are common mistakes in Subtree of Another Tree?

Matching values aren't enough — the whole structure below must match (example 2).