0:00 / 0:00

Are two binary trees identical? Compare the two roots, then trust recursion to compare the left pair and the right pair. A mismatch anywhere ends it.

▼

The problem

LeetCode 100 (Easy). Given the roots of two binary trees p and q, return true if they are the same tree: the same shape, with equal values in every matching node.

Examples (LeetCode's): p = [1,2,3], q = [1,2,3] → true; p = [1,2], q = [1,null,2] → false (the 2 is a left child in p and a right child in q: different shapes); p = [1,2,1], q = [1,1,2] → false (same shape, the children swapped).

TRY IT ON LEETCODE ▶

The solution

def isSameTree(p, q):
    if not p and not q:
        return True
    if not p or not q or p.val != q.val:
        return False
    return (isSameTree(p.left, q.left) and
            isSameTree(p.right, q.right))

Transcript

Same Tree. You get the roots of two binary trees, p and q. Return true if they are the same tree: the same shape, with the same value in every spot. Otherwise, return false.

Three examples. One, two, three against one, two, three: identical, so true. One with a left child two, against one with a right child two: the same values, but different shapes, so false. One, two, one against one, one, two: the same shape, but the children are swapped. False.

A tempting shortcut: write each tree out as a list and compare the lists. But skip the empty spots, and those two different shapes both come out as one, two. You need a marker for every empty spot, and you still build two whole lists before comparing anything.

Instead, walk both trees in lockstep, standing on the same spot in each. If both spots are empty, they match. If only one is empty, or the values differ, it's false. Otherwise, compare the left subtrees, then the right subtrees. The first mismatch stops everything.

In code: if both nodes are null, return true. If only one is null, or the values differ, return false. Then return the left check and the right check. If the left check fails, the right one is never called.

Let's walk example one. One equals one. Go left: two equals two, and its children are both empty, so they match. Go right: three equals three, with two empty children. Seven calls, every spot matched: true. Now example three. The roots match, but on the left, two meets one. False, after just two calls, and the right side is never visited.

Each pair of nodes is checked at most once, so the time is order n. The recursion goes as deep as the tree, so the space is order h, the height of the tree.

Both empty, match. One empty or different, stop. Otherwise, check both sides. That's Same Tree.