Skip to main content
28

Subtree of Another Tree

Easytreesdfs

Your code isn't saved yet: refreshing or leaving the page resets it. Saved progress comes with user accounts.

This problem uses:TreesRead the beginner guide

Given the roots of two binary trees root and subRoot, return true if root contains a subtree that is exactly subRoot, and false otherwise.

Understand the problem

  • A subtree of root is any node in root together with everything below it (all its descendants).
  • You're asking: is there a node in root where, if you "cut out" that node and everything under it, you get a tree identical to subRoot? (Identical means same shape and same values, as in Same Tree.)
  • All descendants count: a matching top part isn't enough if the node in root has extra children below.

Example 1

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

root:     3          subRoot:   4
         / \                   / \
        4   5                 1   2
       / \
      1   2

The 4 in root, with its children 1 and 2, is exactly subRoot.

Example 2

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

root:     3
         / \
        4   5
       / \
      1   2
         /
        0

The 4 looks right at first, but its 2 has an extra child 0. The cut-out subtree is 4, 1, 2, 0, which isn't the same as subRoot.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child.

Constraints

  • 1 <= number of nodes in root <= 2000
  • 1 <= number of nodes in subRoot <= 1000

Hints

Stuck? Open one hint at a time. Each one gives away a little more than the last.

    The idea in one sentence

    Visit every node of the big tree, and at each one run the Same Tree check against subRoot.

    The key insight

    If subRoot appears inside root, it has to start at some node of root. So the problem splits into two questions you can answer separately:

    1. Where to look: every node of root is a candidate starting point. Visit them all with a simple recursive traversal.
    2. What to check there: "is the tree starting at this node exactly the same as subRoot?" That's the Same Tree problem, which you already know.
    text
    isSubtree(node):
      node is empty                   → false (nothing starts here)
      isSameTree(node, subRoot)       → true  (found it)
      otherwise                       → isSubtree(node.left) OR isSubtree(node.right)

    Step by step

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

    Candidate nodeisSameTree(candidate, subRoot)?
    33 ≠ 4 → no
    44 = 4, left 1 = 1 ✅, right: 2 = 2 but root's 2 has a child 0 and subRoot's 2 doesn't → no
    11 ≠ 4 → no
    22 ≠ 4 → no
    00 ≠ 4 → no
    55 ≠ 4 → no

    No candidate matched, so the answer is false.

    The code

    The reference solution is below, with comments on every important line. It contains its own copy of isSameTree.

    How fast is it?

    With n nodes in root and m in subRoot:

    • Time: O(n · m) in the worst case: a Same Tree check of up to m nodes at each of n nodes. In practice, most checks fail on the first node (different value), so it's much faster.
    • Memory: O(h) for the recursion, where h is the height of root.

    Common mistakes

    • Only matching the top part. The candidate's entire subtree must match, including what's below. Same Tree handles this, because it also requires null to match null.
    • Checking only the root. subRoot can start anywhere, so you must try every node.
    • Comparing values instead of structure. Two trees can contain the same values in different shapes.

    Going deeper

    A faster approach: serialize and search. Turn both trees into strings (for example, in preorder), then check whether one string contains the other. With a fast string search like KMP, that's O(n + m). Two details make it correct:

    • Write null markers, or [1, 2] and [1, null, 2] become the same string.
    • Put a separator before each value (like ,12 and ,2), or the tree 12 would "contain" the tree 2.

    Reference solution

    js
    // Same Tree: same shape and same values, all the way down.
    function isSameTree(p, q) {
      if (!p || !q) return p === q // both empty → same; only one empty → different
      return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }
    
    /**
     * @param {TreeNode | null} root
     * @param {TreeNode | null} subRoot
     * @return {boolean}
     */
    export default function isSubtree(root, subRoot) {
      // Ran out of tree: subRoot can't start here.
      if (!root) return false
      // Does the tree starting at THIS node match? If not, try every node below.
      return (
        isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
      )
    }
    ts
    // Same Tree: same shape and same values, all the way down.
    function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
      if (!p || !q) return p === q // both empty → same; only one empty → different
      return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }
    
    export default function isSubtree(root: TreeNode | null, subRoot: TreeNode | null): boolean {
      // Ran out of tree: subRoot can't start here.
      if (!root) return false
      // Does the tree starting at THIS node match? If not, try every node below.
      return (
        isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot)
      )
    }
    python
    def is_same_tree(p: TreeNode | None, q: TreeNode | None) -> bool:
        # Same Tree: same shape and same values, all the way down.
        if p is None or q is None:
            return p is q  # both empty → same; only one empty → different
        return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)
    
    
    def is_subtree(root: TreeNode | None, sub_root: TreeNode | None) -> bool:
        # Ran out of tree: sub_root can't start here.
        if root is None:
            return False
        # Does the tree starting at THIS node match? If not, try every node below.
        return (
            is_same_tree(root, sub_root)
            or is_subtree(root.left, sub_root)
            or is_subtree(root.right, sub_root)
        )