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.
Input: p = [1,2,3], q = [1,2,3]
Output: true
Tree p: Tree q:
1 1
/ \ / \
2 3 2 3
Both trees are identical
Input: p = [1,2], q = [1,null,2]
Output: false
Tree p: Tree q:
1 1
/ \
2 2
Different structure
Input: p = [1,2,1], q = [1,1,2]
Output: false
Tree p: Tree q:
1 1
/ \ / \
2 1 1 2
Different values in children
Two trees are the same if:
This is a perfect fit for recursion with simultaneous traversal.
This is a Tree Comparison problem with:
Base Cases:
Recursive Case:
Why this works:
isSameTree(p, q):
if not p and not q: return True
if not p or not q: return False
if p.val != q.val: return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)
Time: O(min(n, m)) where n, m = number of nodes in each tree
Space: O(min(h₁, h₂)) where h₁, h₂ = heights
1class TreeNode {
2 int val;
3 TreeNode left;
4 TreeNode right;
5 TreeNode() {}
6 TreeNode(int val) { this.val = val; }
7 TreeNode(int val, TreeNode left, TreeNode right) {
8 this.val = val;
9 this.left = left;
10 this.right = right;
11 }
12}
13
14class Solution {
15 public boolean isSameTree(TreeNode p, TreeNode q) {
16 // Both null - same
17 if (p == null && q == null) {
18 return true;
19 }
20
21 // One null, one not - different
22 if (p == null || q == null) {
23 return false;
24 }
25
26 // Different values - different
27 if (p.val != q.val) {
28 return false;
29 }
30
31 // Check both subtrees recursively
32 return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
33 }
34}
35