Subtree of Another Tree

Easy

Topics
TreeDFSString Matching

Given the roots of two binary trees root and subRoot, return true if subRoot appears as a subtree of root (a node of root plus all its descendants matches subRoot exactly).

Example 1

root14235
subRoot142
The shaded part of the first tree matches the second exactly, all the way down to its leaves — a partial match at the top does not count. So the answer is true.
Tree given in level-order (breadth-first); null marks a missing child.
Input:  root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true

Example 2

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

Constraints

  • 1 <= root nodes <= 2000
  • 1 <= subRoot nodes <= 1000
  • -10^4 <= Node.val <= 10^4
Editorial — intuition, approach, complexity and pitfalls

Intuition

At every node of the big tree, ask "is the subtree rooted here identical to subRoot?" That inner check is just the Same Tree comparison.

Approach

  1. Write a sameTree(a, b) helper.
  2. Traverse root; at each node test sameTree(node, subRoot).
  3. Return true if any node matches.

Dry Run

root = 3 4 5 1 2        subRoot = 4 1 2
      3                4
     / \              / \
    4   5            1   2
   / \
  1   2
The outer walk asks the same question at every node, and the inner `same` answers
it:
  same(node 3, subRoot)   3 != 4, fails on the very first comparison   -> false
  same(node 4, subRoot)   4 == 4, then 1 == 1, then 2 == 2             -> true
answer true, found at the second node tested
That is where the O(m * n) comes from, and the trace shows both halves of it. Most
calls to `same` die on the root comparison and cost O(1); the one that matches
walks all of subRoot. In the worst case -- a big tree whose every node has the same
value as subRoot's root -- every one of the m calls walks all n nodes.
The near-miss is worth running too. Add a single 0 beneath the 2, so root becomes
3 4 5 1 2 null null null null 0, and the answer flips to false. `same` requires
structural identity, not containment: the node 4 now has an extra descendant that
subRoot does not, so matching values down to subRoot's leaves is not enough.
`if not q: return True` has to come before `if not p`. An empty subRoot is a
subtree of anything, including an empty tree, and testing p first would return
false for that pair.

Complexity

  • Time — O(m*n): each of m nodes may trigger an O(n) comparison.
  • Space — O(h): recursion stack.

Common Pitfalls

  • An empty subRoot is a subtree of anything; handle it before dereferencing.

Full Solution — all languages

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution:
    def isSubtree(self, p, q):
        def same(a,b):
            if not a and not b: return True
            if not a or not b or a.val!=b.val: return False
            return same(a.left,b.left) and same(a.right,b.right)
        if not q: return True
        if not p: return False
        if same(p,q): return True
        return self.isSubtree(p.left,q) or self.isSubtree(p.right,q)
Asked at eBay
SensAI
Beta
Tap the mic to stop voice mode