Skip to main content
Back to problems
Leetcode
Medium
Trees
Recursion
Strings
Google
Amazon
Microsoft
Subtree Of Another Tree

Determine whether one binary tree appears as a subtree of another binary tree.

Acceptance 100%
Problem Statement

Problem

Given the roots of two binary trees root and subRoot, determine whether subRoot is a subtree of root.

A tree subRoot is considered a subtree of root if there exists a node in root such that the entire tree rooted at that node has the same structure and node values as subRoot.

Two trees are the same when they are both empty or when their roots have equal values and their left and right subtrees are also the same.

Goal

Return true if subRoot is a subtree of root; otherwise, return false.

Input Format

Input Format

  • Two binary tree roots: root and subRoot.
  • Each tree node contains an integer value and optional left/right children.

Output Format

Output Format

  • Return a boolean value:
    • true if subRoot is a subtree of root
    • false otherwise

Constraints

Constraints

  • The trees may be empty.
  • Node values are integers.
  • You may assume the trees fit in memory.
  • A valid solution should avoid unnecessary re-computation when checking repeated candidate nodes.
Examples
Sample cases returned by the problem API.

Example 1

Input

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

Output

true

Explanation

The tree rooted at the node with value 4 has the same structure and values as subRoot.

Example 2

Input

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

Output

false

Explanation

Although root contains a node with value 4, its subtree does not match subRoot because of the extra node 0.

Premium problem context

Unlock deeper context for this problem

Premium adds guided hints, editorial links, similar variants, discussion resources, and concept maps so you can understand why a problem matters, not just solve it once.

Guided hints
Editorial and discussion links
Concept map and variants
Sign in to unlock
Track your progress
Sign in to bookmark this problem, save notes, and manage its revision plan.