剑指offer58.对称的二叉树

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_36811967/article/details/87920043

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

注意镜像的定义:

# -*- coding:utf-8 -*-
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    def isSymmetrical(self, pRoot):
        # write code here
        # 左子树的左子树和右子树的右子树比较,右子树的左子树和左子树的右子树比较
        if not pRoot:
            return True
        return self.symmetrical(pRoot.left, pRoot.right)

    def symmetrical(self, a, b):
        if not a:
            return not b
        return b and a.val == b.val and \
               self.symmetrical(a.left, b.right) and self.symmetrical(a.right, b.left)

猜你喜欢

转载自blog.csdn.net/sinat_36811967/article/details/87920043