Skip to main content
All Questions

Given two binary trees, decide whether the second appears as a subtree of the first (same structure and values from some node down). Then optimise your solution.

Easy
Unlock detailed company stats for this questionUpgrade

Given the roots of two binary trees, root and sub_root, return true if root contains a subtree with exactly the same shape and values as sub_root, and false otherwise.

A subtree of root is any node in root together with all of its descendants. A tree also counts as a subtree of itself.

Trees in the examples and tests are written in level order, with null for a missing child.

Example 1

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

The node 4 in root has children 1 and 2, matching sub_root exactly.

Example 2

Input: root = [3, 4, 5, 1, 2, null, null, null, null, 0], sub_root = [4, 1, 2] Output: false

The node 4 in root has an extra descendant, 0, so its subtree doesn't match.

Constraints

  • root has between 1 and 2000 nodes, and sub_root has between 1 and 1000 nodes.
  • -10^4 <= Node.val <= 10^4

Related courses

Course

SQL Interview Prep Course

Prepare for SQL interviews with lessons on joins, aggregations, and window functions, then practice real SQL interview questions in an interactive editor with expert solutions.

Course

Data Science Interview Prep

Land your dream data science role at Google, Amazon, Microsoft, Meta, Apple, and other top companies. Learn from mock interviews, frameworks, and advice from senior candidates. Practice statistics, experimentation, coding, SQL, machine learning, behavioral interviews, and more.