leetcode 101. 对称二叉树(python)

给定一个二叉树,检查它是否是镜像对称的。

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

    1
   / \
  2   2
 / \ / \
3  4 4  3

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

    1
   / \
  2   2
   \   \
   3    3

说明:

如果你可以运用递归和迭代两种方法解决这个问题,会很加分。


# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
 
class Solution:
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: 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#and操作,需要l与r皆为true时,才返回真。只用最后一次递归边界return值  
            else:  
                return False
        if not root:
            return True
        else:
            return isSameTree(root.left,root.right)

猜你喜欢

转载自blog.csdn.net/weixin_40449300/article/details/81163616