ยท 1 min read
Blind 75 - Same Tree
Placeholder
[Video]
Check if two trees have the same elements in the same positions.
Approaches
O(n) time; O(1) space; 8 lines
This is a preferred solution.
I was originally trying the iterative approach, which was too complex.
Source: Java Solution better than 100% - LeetCode Discuss
public boolean isSameTree(TreeNode p, TreeNode q) {
if(p==null && q==null){
return true;
}
if(p== null || q == null){
return false;
}
return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Code optimization: null checks can become a single block
Optimized
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);
}Related posts
- Blind 75 - Reverse LinkedList Nov 16, 2022
- Blind 75 - Product of Array Except Self Nov 4, 2022
- Blind 75 - Contains Duplicate Oct 30, 2022
Get new posts by email
No spam. Unsubscribe anytime. Or grab the RSS feed.
Mailto-based for now. ButtonDown / ConvertKit can replace this form later.