Skip to content

Instantly share code, notes, and snippets.

@wanderindev
Created July 9, 2022 21:36
Show Gist options
  • Save wanderindev/b5ab356faae6a5209c8b3a0dd0ebfe0a to your computer and use it in GitHub Desktop.
Save wanderindev/b5ab356faae6a5209c8b3a0dd0ebfe0a to your computer and use it in GitHub Desktop.
class TreeNode(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution(object):
def is_same_tree(self, p, q):
"""
:type p: TreeNode
:type q: TreeNode
:rtype: bool
"""
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
left_equal = self.is_same_tree(p.left, q.left)
right_equal = self.is_same_tree(p.right, q.right)
return left_equal and right_equal
# Test cases
sol = Solution()
p = TreeNode(1)
p.left = TreeNode(2)
p.right = TreeNode(3)
q = TreeNode(1)
q.left = TreeNode(2)
q.right = TreeNode(3)
assert sol.is_same_tree(p, q)
p = TreeNode(1)
p.left = TreeNode(2)
q = TreeNode(1)
q.left = None
q.right = TreeNode(2)
assert not sol.is_same_tree(p, q)
p = TreeNode(1)
p.left = TreeNode(2)
p.right = TreeNode(1)
q = TreeNode(1)
q.left = TreeNode(1)
q.right = TreeNode(2)
assert not sol.is_same_tree(p, q)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment