from typing import Optional
from publicmatt.leet import TreeNode
def is_same_tree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
def compare(left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
return (
left.val == right.val
and compare(left.left, right.left)
and compare(left.right, right.right)
)
return compare(p, q)
Tests
from publicmatt.leet import TreeNode
from publicmatt.leet.problems.same_tree import is_same_tree
def test_simple_same():
p = TreeNode.from_list([1, 2, 3])
q = TreeNode.from_list([1, 2, 3])
assert is_same_tree(p, q)
def test_simple_hole():
p = TreeNode.from_list([1, 2])
q = TreeNode.from_list([1, None, 2])
assert not is_same_tree(p, q)
def test_mirrored_tree():
p = TreeNode.from_list([1, 2, 1])
q = TreeNode.from_list([1, 1, 2])
assert not is_same_tree(p, q)