class Solution1:
    def isSymmetric(self, root: TreeNode) -> bool:

        if not root:
            return True
        stack = [(root.left, root.right)]
        while stack:
            p, q = stack.pop()
            if not p and not q:
                continue
            if not p or not q or p.val != q.val:
                return False
            stack.append((p.left, q.right))
            stack.append((p.right, q.left))
        return True


@pytest.mark.parametrize("args,expected", [
    (TreeNode.initTreeSimple([1, 2, 2], [(0, 1)], [(0, 2)]), True),
    (TreeNode.initTreeSimple([1, None, 2, 4], [(2, 3)], [(0, 2)]), False),
])
def test_solutions(args, expected):
    assert Solution().isSymmetric(args) == expected
    assert Solution1().isSymmetric(args) == expected


if __name__ == '__main__':
    pytest.main(["-q", "--color=yes", "--capture=no", __file__])
Exemple #2
0
        return isValidRecursive(root)


class Solution2(object):
    def isValidBST(self, root):
        return self.isValidBSTRecu(root, float("-inf"), float("inf"))

    def isValidBSTRecu(self, root, low, high):
        if root is None:
            return True

        return low < root.val  < high \
               and self.isValidBSTRecu(root.left, low, root.val) \
               and self.isValidBSTRecu(root.right, root.val, high)


@pytest.mark.parametrize("args,expected", [
    (TreeNode.initTreeSimple([2, 1, 3], [(1, 0)], [(1, 2)]), True),
    (TreeNode.initTreeSimple([1, None, 2, 3], [(2, 3)], [(0, 2)]), False),
    (TreeNode.initTreeSimple([3, 9, 20, None, None, 15, 7], [(0, 1), (2, 5)],
                             [(0, 2), (2, 6)]), False),
])
def test_solutions(args, expected):
    assert Solution().isValidBST(args) == expected
    assert Solution2().isValidBST(args) == expected


if __name__ == '__main__':
    pytest.main(["-q", "--color=yes", "--capture=no", __file__])