Problem
Section titled “Problem”Given the roots of two binary trees p and q, write a function to check if they are the same or not.
Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.
Example 1:

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

Input: p = [1,2], q = [1,null,2]Output: falseExample 3:

Input: p = [1,2,1], q = [1,1,2]Output: falseConstraints:
- The number of nodes in both trees is in the range
[0, 100]. -
Node.val
Solution approach
Section titled “Solution approach”Intuition
Section titled “Intuition”Two trees are the same exactly when their roots match and their left subtrees are the same and their right subtrees are the same. That definition is already recursive, so the code mirrors it: walk both trees in lockstep and compare the pair of nodes at each position.
“Roots match” has three cases: both missing (equal — an empty tree equals an empty tree), exactly one missing (the shapes differ), or both present with equal values.
Algorithm
Section titled “Algorithm”- If
pandqare both null, returntrue. - If exactly one is null, or
p->val != q->val, returnfalse. - Return
isSameTree(p->left, q->left) && isSameTree(p->right, q->right). The&&short-circuits, so the search stops at the first mismatch.
Complexity
Section titled “Complexity”Let be the number of nodes in the smaller tree and its height.
- Time: — each pair of positions is compared at most once, and the walk stops as soon as one tree runs out where the other does not.
- Space: — the recursion stack; for a degenerate (list-shaped) tree, for a balanced one.
Edge cases
Section titled “Edge cases”- Both trees empty: step 1 returns
true. - Same values, different shape (Example 2): at the root’s left child
phas a node andqhas null, so step 2 returnsfalse. - Same shape, values swapped (Example 3): the left children are
2and1, so step 2 returnsfalse.
Think before you peek
Work out an approach on your own first — the explanation will still be here when you want it.
class Solution { public: bool isSameTree(TreeNode* p, TreeNode* q) { if (!p && !q) return true; if (!p || !q || p->val != q->val) return false; return isSameTree(p->left, q->left) && isSameTree(p->right, q->right); }};class Solution { public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null || p.val != q.val) return false; return isSameTree(p.left, q.left) && isSameTree(p.right, q.right); }}class Solution: def isSameTree(self, p: TreeNode | None, q: TreeNode | None) -> bool: if not p and not q: return True if not p or not q or p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)Give it a try first
Attempt the problem on LeetCode — the code will still be here.