LeetCode101-对称二叉树-Python3

题目

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

例如,二叉树 [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

思路

递归法,关键在于 return p.val == q.val and self.recursion(p.left, q.right) and self.recursion(p.right, q.left)

Python3代码

# 定义二叉树节点
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
        """
        if root:
            return self.recursion(root.left, root.right)
        else:
            return True

    def recursion(self, p, q):
        if p and q:
            return p.val == q.val and self.recursion(p.left, q.right) and self.recursion(p.right, q.left)
        else:
            return not p and not q

猜你喜欢

转载自blog.csdn.net/weixin_42762089/article/details/86619732