InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Subtree of Another Tree

easy Original ↗ 00:00

Problem

Given the roots of two binary trees root and subRoot, return True if some subtree of root is identical to subRoot (same structure and same values), and False otherwise.

A subtree of root is a node in root together with all of that node’s descendants; you cannot omit any descendant. The whole tree counts as a subtree of itself.

Examples

Example 1

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

The subtree rooted at root’s node 4 is exactly [4,1,2].

Example 2

Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: False

Root’s node 4 now has an extra 0 hanging under its child 2, so its subtree is [4,1,2,null,null,0] — a match must include every descendant.

Example 3

Input: root = [1,1], subRoot = [1]
Output: True

The left child of root is a single node 1, identical to subRoot.

Constraints

  • Nodes in root: [1, 2000]; nodes in subRoot: [1, 1000].
  • -10^4 <= Node.val <= 10^4 (values are not distinct — several candidates may share subRoot’s root value).

Bounds are small enough that an O(n·m) solution passes, but the follow-up question is how to beat it.

Think about it first

Hint 1 If you already had a helper that decides whether two trees are identical, how would you use it here?
Hint 2 Try the identity check at the current node of root; if it fails, where else could a match start? Beware Example 2: matching the root values is not enough to commit to a candidate.
Hint 3 `isSubtree(root, subRoot)` = `isSameTree(root, subRoot)` OR `isSubtree(root.left, subRoot)` OR `isSubtree(root.right, subRoot)`. For the O(n+m) follow-up, think about serializing both trees (with null markers) and doing a substring search.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug