Skip to main content
27

Same 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 p and q, return true if they are the same, and false otherwise.

Understand the problem

Two trees are the same when both of these hold:

  1. Same shape: wherever one tree has a node, the other has a node in exactly the same position (same side, same level).
  2. Same values: the nodes in matching positions hold equal values.

Imagine laying one tree exactly on top of the other: every node must line up with an identical node.

Example 1

text
Input:  p = [1, 2, 3], q = [1, 2, 3]
Output: true

  1       1
 / \     / \
2   3   2   3

Example 2

text
Input:  p = [1, 2], q = [1, null, 2]
Output: false

  1       1
 /         \
2           2

Same values, but 2 is a left child in p and a right child in q. Different shapes.

Example 3

text
Input:  p = [1, 2, 1], q = [1, 1, 2]
Output: false

Same shape, but the children's values are swapped.

How trees are written in the tests: level by level, top to bottom, left to right, with null for a missing child. [] is an empty tree.

Constraints

  • 0 <= number of nodes in each tree <= 100

Hints

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

    The idea in one sentence

    Walk both trees together: at each pair of nodes, check they're both empty, or both present with equal values and recursively the same left and right subtrees.

    Thinking recursively

    Two trees are the same when:

    • their roots have the same value, and
    • their left subtrees are the same, and
    • their right subtrees are the same.

    The last two are the same question about smaller trees, so recursion handles them.

    Base cases (where we stop, with no recursion):

    pqAnswer
    nullnulltrue: two empty trees are the same
    nulla nodefalse: one has a node where the other doesn't
    a nodenullfalse

    Step by step

    p = [1, 2] (2 on the left), q = [1, null, 2] (2 on the right):

    ComparingWhat happensResult
    p:1 vs q:1values match → compare left children
    p:2 vs nullone is null, the other isn'tfalse
    back at the rootsleft subtrees differ, no need to check rightfalse

    The answer is false, and we stopped at the first difference.

    The code

    The reference solution is below, with comments on every important line.

    How fast is it?

    • Time: O(min(n, m)). In the worst case (identical trees) every node is compared once; otherwise we stop at the first difference.
    • Memory: O(h) for the recursion, where h is the height.

    Common mistakes

    • Reading .val before checking for null. Always handle the empty cases first.
    • Comparing only the values in order (e.g. by flattening both trees into arrays). [1, 2] and [1, null, 2] contain the same values in the same order, but have different shapes. Null markers would be needed to make that work.
    • Using || instead of &&. Both subtrees must match, not just one.

    Going deeper

    This little function is a building block: Subtree of Another Tree runs it at every node of a bigger tree. Comparing two structures side by side with recursion also shows up when checking if a tree is symmetric (compare the left subtree with the mirror of the right).

    Reference solution

    js
    /**
     * @param {TreeNode | null} p
     * @param {TreeNode | null} q
     * @return {boolean}
     */
    export default function isSameTree(p, q) {
      // At least one is empty: they're the same only if BOTH are empty.
      // (Checked first, so we never read .val of null.)
      if (!p || !q) return p === q
      // Same value here, and the same left subtrees, and the same right subtrees.
      return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }
    ts
    export default function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
      // At least one is empty: they're the same only if BOTH are empty.
      // (Checked first, so we never read .val of null.)
      if (!p || !q) return p === q
      // Same value here, and the same left subtrees, and the same right subtrees.
      return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right)
    }
    python
    def is_same_tree(p: TreeNode | None, q: TreeNode | None) -> bool:
        # At least one is empty: they're the same only if BOTH are empty.
        # (Checked first, so we never read .val of None.)
        if p is None or q is None:
            return p is q
        # Same value here, and the same left subtrees, and the same right subtrees.
        return p.val == q.val and is_same_tree(p.left, q.left) and is_same_tree(p.right, q.right)