Same Tree (LeetCode 100): Solution and Explanation
Given the roots of two binary trees, decide whether they are identical. Two trees count as the same only when they have exactly the same shape and every pair of corresponding nodes holds the same value.
Watch it run step by step
Try your own input and write the code →Intuition
A tempting shortcut is to serialize both trees with an inorder traversal and compare the resulting lists. That fails, because different shapes can produce the same inorder sequence: a root 1 with left child 2 and a root 2 with right child 1 both read as [2, 1]. Any comparison has to respect structure, not just values.
The cleaner way to think about it is recursively. Two trees are the same exactly when their roots match, their left subtrees are the same, and their right subtrees are the same. That definition is already an algorithm. You compare the current pair of nodes and then ask the same question about the left pair and the right pair.
The only care needed is in the base cases. If both nodes are missing, that branch matches. If exactly one is missing, the shapes differ. If both exist but hold different values, the trees differ. Once those three checks pass, the answer depends entirely on the two recursive calls, and the and operator stops early as soon as one side reports a mismatch.
Approach: Recursive DFS comparison
- If both
pandqare None, return True because two empty trees are identical. - If only one of them is None, return False because the shapes differ at this position.
- If both exist but
p.val != q.val, return False because the values differ. - Otherwise recurse on the left children,
isSameTree(p.left, q.left). - Recurse on the right children,
isSameTree(p.right, q.right), and return True only if both recursive calls return True.
Step-by-step example
p = [1,2,3], q = [1,2,3]
- Compare the roots: both exist and both hold 1, so move on to the children.
- Compare the left children: both hold 2. Their own children are all None, so each of those calls returns True, and the left subtree matches.
- Compare the right children: both hold 3, and again their children are all None, so the right subtree matches.
- Both recursive results are True, so the root call returns True and the trees are the same.
- If instead q were [1,null,2], the left comparison would see 2 against None and return False, and the
andwould skip the right side entirely.
Code: Python, Java, C++
1class Solution:
2 def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
3 if not p and not q:
4 return True
5 if not p or not q or p.val != q.val:
6 return False
7 return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)1class Solution {
2 public boolean isSameTree(TreeNode p, TreeNode q) {
3 if (p == null && q == null) return true;
4 if (p == null || q == null || p.val != q.val) return false;
5 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
6 }
7}1class Solution {
2public:
3 bool isSameTree(TreeNode* p, TreeNode* q) {
4 if (!p && !q) return true;
5 if (!p || !q || p->val != q->val) return false;
6 return isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
7 }
8};Time and space complexity
O(n)
Each pair of corresponding nodes is compared at most once, and the recursion stops at the first mismatch. In the worst case the trees are identical and every node is visited, where n is the number of nodes in the smaller tree.
O(h)
The recursion stack grows to the height h of the trees. That is O(log n) for a balanced tree and O(n) for a tree shaped like a linked list.
Other approaches
Iterative BFS with a queue of pairs (time O(n), space O(w))
Push the pair (p, q) onto a queue, then repeatedly pop a pair, apply the same three checks, and push the left pair and right pair. It avoids recursion depth limits on very deep trees and gives the same answer.
Serialize with null markers (time O(n), space O(n))
Produce a preorder string of each tree that includes a marker for every missing child, then compare the strings. With the null markers the serialization is unique to the shape, but it builds two strings of linear size.
Common mistakes
- Checking
p.val != q.valbefore checking for None. Accessing.valon a missing node crashes, so the None checks must come first. - Writing the second base case as
if not p and q, which forgets the symmetric case wherepexists andqdoes not. - Comparing only inorder or only preorder value lists without null markers. Different shapes can produce identical value sequences.
- Using
orinstead ofandwhen combining the two recursive results, which would accept trees where only one side matches.
Frequently asked questions
What is the time complexity of Same Tree?
It is O(n), where n is the number of nodes in the smaller tree. Each pair of nodes is compared once, and the recursion stops as soon as it finds a difference.
Can you solve Same Tree iteratively?
Yes. Use a stack or queue holding pairs of nodes, starting with the two roots. Pop a pair, run the same None and value checks, and push the pairs of left children and right children until the container is empty.
Why isn't comparing inorder traversals enough?
Inorder traversal loses information about shape. Two trees with different structures can list the same values in the same order, so you need either a structural recursive comparison or a serialization that records missing children.