Given the roots of two binary trees
pandq, 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.
Constraints:
- The number of nodes in both trees is in the range
[0, 100].-104 <= Node.val <= 104
This is a classic tree problem. If two trees are the same, then at the corresponding nodes:
def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
if p is None and q is None:
return True
elif (p is None and q is not None) or (p is not None and q is None):
return False
elif p.val != q.val:
return False
else:
return (self.isSameTree(p.left, q.left)
and self.isSameTree(p.right, q.right))
Notice at every node there are only constant time operations. The algorithm recurses through every node, stopping only if the trees do not match or an empty node is reached. Therefore the algorithm has run time complexity.
Since the algorithm in the worst case recurses through all nodes before returning, the space complexity is , since each recursive call uses constant space.