↻one more pass.
Trees · Easy

Same Tree: the idea to remember.

Determine whether two binary trees have identical shape and node values.

Solve on LeetCode ↗

The core insight

Compare corresponding nodes and recursively compare both corresponding children.

Why it works

Equality requires the current values and both entire child pairs to match.

The mistake to avoid

Comparing traversal values without null markers can lose structural information.

Time: O(min(n, m)) until mismatch; O(n) for equal treesSpace: O(min(h₁, h₂)) call stack

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

boolean isSameTree(TreeNode p, TreeNode q) {
    if (p == null || q == null) return p == q;
    return p.val == q.val
        && isSameTree(p.left, q.left)
        && isSameTree(p.right, q.right);
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.