EasyNo. 0572

Subtree of Another Tree — LeetCode 572 Python Solution

Topics
Tree, Depth-First Search, Binary Tree, String Matching, Hash Function
On study lists
Blind 75 and NeetCode 150
Reading time
4 min

The problem

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values of subRoot and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants.

Example

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

Python solution

PythonSolution
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def same(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
            if p is None or q is None:
                return p is q
            return p.val == q.val and same(p.left, q.left) and same(p.right, q.right)

        if root is None:
            return False
        return (
            same(root, subRoot)
            or self.isSubtree(root.left, subRoot)
            or self.isSubtree(root.right, subRoot)
        )

Complexity

Time
O(n × m)
Space · auxiliary
O(n)

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 572. Subtree of Another Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0563Binary Tree TiltEasy
0098Validate Binary Search TreeMedium
0099Recover Binary Search TreeMedium
0100Same TreeEasy
0101Symmetric TreeEasy
0104Maximum Depth of Binary TreeEasy

Frequently asked questions

How hard is LeetCode 572. Subtree of Another Tree?

LeetCode 572. Subtree of Another Tree is rated Easy on LeetCode.

What is the time complexity of LeetCode 572. Subtree of Another Tree?

The Python solution on this page runs in O(n × m).

What is the space complexity of LeetCode 572. Subtree of Another Tree?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 572. Subtree of Another Tree cover?

LeetCode 572. Subtree of Another Tree is tagged Tree, Depth-First Search, Binary Tree, String Matching and Hash Function on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.