Subtree of Another Tree

EasyTree recursionLeetCode 572 ↗World 3-7
0:00 / 0:00

Check if one binary tree appears inside another. Try every node as a starting point and run a same-tree check from there.

▼

The problem

LeetCode 572 (Easy). Given the roots of two binary trees root and subRoot, return true if there is a node in root whose subtree (that node and all its descendants) has the same structure and the same values as subRoot.

Examples (LeetCode's, both animated): root = [3,4,5,1,2], subRoot = [4,1,2] → true (the subtree at 4); root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2] → false (node 2 has an extra child 0, so the subtree at 4 doesn't match all the way down).

TRY IT ON LEETCODE ▶

The solution

def isSubtree(root, subRoot):
    if not root:
        return False
    if sameTree(root, subRoot):
        return True
    return (isSubtree(root.left, subRoot) or
            isSubtree(root.right, subRoot))

def sameTree(a, b):
    if not a and not b:
        return True
    if not a or not b or a.val != b.val:
        return False
    return (sameTree(a.left, b.left) and
            sameTree(a.right, b.right))

Transcript

Subtree of Another Tree. You get two binary trees, a big one and a small one. Is the small one a subtree of the big one? Some node of the big tree, with everything below it, must match the small tree exactly.

Picture the big tree as a star chart, and the small one etched on a glass template. The chart is three, four, five, one, two; the template is four, one, two. Lay it on star four: everything lines up. True.

Now give star two a child, zero. The template ends at two, but the chart keeps going. A subtree takes everything below its root, so this one is false.

Matching values alone isn't enough: four, one and two are still there. Matching shape alone fails too. Values and shape must match, all the way down.

So ask two questions. Are two trees the same? Yes when both are empty, or when their roots match and both pairs of subtrees are the same. Then try that check at every star of the chart.

In code, an empty chart returns false. If the same tree check passes here, return true; otherwise, try the left side, then the right. The helper returns true when both nodes are empty, false when only one is or the values differ, and otherwise checks both pairs of children.

Now the second chart. Star three isn't four, so it fails at once. At star four, four, one and two match, but below two the chart has a zero, and the template has nothing. Stars one, two, zero and five aren't four. No star passed, so the answer is false.

With m stars in the chart and n in the template, each check takes up to n steps at each of m stars: order m times n time. The recursion goes as deep as the chart is tall: order h space. Serializing both trees and matching strings with KMP gets order m plus n.

Every star, one same tree check. That's Subtree of Another Tree.