same_tree.py 414 B

12345678910111213
  1. from typing import Optional
  2. from tree import TreeNode
  3. class Solution:
  4. def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
  5. if not p and not q:
  6. return True
  7. elif not p or not q:
  8. return False
  9. elif p.val != q.val:
  10. return False
  11. else:
  12. return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)