判断是否是对称二叉搜索树

问题:

# 给定一个二叉树,检查它是否是镜像对称的。 
#
#
#
# 例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

方法:递归

# leetcode submit region begin(Prohibit modification and deletion)
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def isSameTree(p, q):
            if not p and not q:
                return True
            if p and q and p.val == q.val:
                l = isSameTree(p.left, q.right)
                r = isSameTree(p.right, q.left)
                return l and r
            else:
                return False

        if not root:
            return True
        else:
            return isSameTree(root.left, root.right)
# leetcode submit region end(Prohibit modification and deletion)

 

posted @ 2021-09-03 16:14  今夜无风  阅读(35)  评论(0编辑  收藏  举报