InterviewPrepKit

Home / Coding / Trees

Subtree of Another Tree

easy Original ↗
Solving tips
  • Reduce to a subroutine: isSubtree = isSameTree at this node OR isSubtree(left) OR isSubtree(right), reusing the Same Tree lockstep check.
  • Don't commit to the first node whose value equals subRoot's root; values repeat, so a failed candidate means keep searching elsewhere.
  • Brute force is O(n*m) time / O(h) space, fine for the bounds; the O(n+m) follow-up serializes both trees (with null markers and value delimiters) and does substring search via KMP.
  • Get the base cases right: an empty subRoot is a subtree of anything, but an empty root only contains an empty subRoot.

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 cut branches off. 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.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.