p
q
Call stack one frame per isSameTree(p, q) call, shown as p,q · N = null · badges = returned ✓ / ✗
public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) { return true; } if (p != null && q != null && p.val == q.val) { return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); } return false;}
- p
- —
- q
- —
- left
- —
- right
- —
- return
- —
Why it works
- Brute force serializes both trees with null markers and compares the strings. Also O(n), but it builds two full strings even when the roots already differ.
- Two trees are the same exactly when the roots match and the left subtrees are the same and the right subtrees are the same. The code is that sentence, walked in lockstep on matching positions.
- Each pair of nodes is compared once, and the walk stops at the first mismatch thanks to
&&: O(min(n, m)) time, O(h) stack. - Pitfall: checking only values. A null against a node is a mismatch even if every value matches, as in
[1,2]vs[1,null,2]. The two null checks must come beforep.valis read. - Next: Subtree of Another Tree (572) runs this exact check from every node of the bigger tree.