100. Same Tree
Problem
Decide whether two binary trees p and q are identical: the same shape with the same value in every corresponding node.
Example: [1,2,3] and [1,2,3] → true; [1,2] and [1,null,2] → false
Both null → true; one null or values differ → false; else recurse on both sides.
Complexity: O(n).
class Solution:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if not p or not q:
return p is q
return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
assert Solution().isSameTree(make_tree([1, 2, 3]), make_tree([1, 2, 3])) is True
assert Solution().isSameTree(make_tree([1, 2]), make_tree([1, None, 2])) is False
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);
}
}
func isSameTree(p *TreeNode, q *TreeNode) bool {
if p == nil || q == nil {
return p == q
}
return p.Val == q.Val && isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)
}