Same Tree
Same Tree is a easy trees & bst problem solved with the recursion pattern.
The best approach, recursive, runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from iterative (queue of pairs) up.
Problem
Given the roots of two binary trees, decide whether they are identical: same shape and same values in every position.
Examples
Example 1
- Input
p = [1, 2, 3], q = [1, 2, 3]- Output
true
Example 2
- Input
p = [1, 2], q = [1, null, 2]- Output
false- Why
- Same values, different shape.
Constraints
- Each tree has
0to100nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Iterative (queue of pairs) | O(n) | O(n) |
| Recursive | O(n) | O(h) |
1Iterative (queue of pairs)
O(n)O(n)Compare nodes pairwise with a queue.
- Queue (p, q). Poll a pair; both null → continue; one null or values differ → false.
- Add (left, left) and (right, right).
class Solution {
public boolean isSameTree(TreeNode p, TreeNode q) {
Deque<TreeNode[]> dq = new ArrayDeque<>();
dq.add(new TreeNode[] { p, q });
while (!dq.isEmpty()) {
TreeNode[] pair = dq.poll();
TreeNode a = pair[0], b = pair[1];
if (a == null && b == null) continue;
if (a == null || b == null || a.val != b.val) return false;
dq.add(new TreeNode[] { a.left, b.left });
dq.add(new TreeNode[] { a.right, b.right });
}
return true;
}
}class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
dq = deque([(p, q)])
while dq:
a, b = dq.popleft()
if a is None and b is None:
continue
if a is None or b is None or a.val != b.val:
return False
dq.append((a.left, b.left))
dq.append((a.right, b.right))
return Trueclass Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
queue<pair<TreeNode*, TreeNode*>> dq;
dq.push({ p, q });
while (!dq.empty()) {
auto [a, b] = dq.front(); dq.pop();
if (a == nullptr && b == nullptr) continue;
if (a == nullptr || b == nullptr || a->val != b->val) return false;
dq.push({ a->left, b->left });
dq.push({ a->right, b->right });
}
return true;
}
};function isSameTree(p, q) {
const dq = [[p, q]];
let head = 0;
while (head < dq.length) {
const [a, b] = dq[head++];
if (a === null && b === null) continue;
if (a === null || b === null || a.val !== b.val) return false;
dq.push([a.left, b.left]);
dq.push([a.right, b.right]);
}
return true;
}2Recursive
O(n)O(h)Both null: equal. Exactly one null or different values: not equal. Otherwise compare both left subtrees and both right subtrees.
- if p == null || q == null return p == q.
- return p.val == q.val && same(p.left, q.left) && same(p.right, q.right).
class Solution {
public 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);
}
}class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None or q is None:
return p is q
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)class Solution {
public:
bool isSameTree(TreeNode* p, TreeNode* q) {
if (p == nullptr || q == nullptr) return p == q;
return p->val == q->val && isSameTree(p->left, q->left) && isSameTree(p->right, q->right);
}
};function isSameTree(p, q) {
if (p === null || q === null) return p === q;
return p.val === q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Edge cases to test
- Both empty (true)
- One empty, one not
Hints
Hint 1
Two trees are equal if the roots match and both pairs of subtrees are equal.
FAQ
What is the best time complexity for Same Tree?
Recursive runs in O(n) time and O(h) extra space.
Which pattern does Same Tree use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Preorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive).
Is there a brute force solution for Same Tree?
Yes. Iterative (queue of pairs) takes O(n) time and O(n) space. Compare nodes pairwise with a queue.
Which edge cases should I test for Same Tree?
Both empty (true); One empty, one not.