import os import sys sys.path.append(os.path.dirname(os.path.dirname(__file__))) from _utils.binary_tree import build_tree from solution import Solution
null = None
@pytest.mark.parametrize('p, q, expected', [ ([1,2,3], [1,2,3], True), ([1,2], [1,null,2], False), ([1,2,1], [1,1,2], False), ]) classTest: deftest_solution(self, p, q, expected): sol = Solution() assert sol.isSameTree(build_tree(p), build_tree(q)) == expected
# Definition for a binary tree node. classTreeNode: def__init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right
classSolution: defisSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool: stack = [] while p or q or stack: if (notnot p) != (notnot q): returnFalse elif p: if p.val != q.val: returnFalse stack.append((p, q)) p = p.left q = q.left elif stack: p, q = stack.pop() p = p.right q = q.right