剑指Offer58:对称的二叉树

思路:

# -*- 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
        def is_same(p1,p2):
            if not p1 and not p2:
                return True
            if (p1 and p2) and p1.val==p2.val:
                return is_same(p1.left,p2.right) and is_same(p1.right,p2.left)
            return False
        if not pRoot: 
            return True
        if pRoot.left and not pRoot.right:#左子树存在,右子树不存在
            return False
        if not pRoot.left and pRoot.right:#左子树不存在,右子树存在
            return False
        return is_same(pRoot.left,pRoot.right)

猜你喜欢

转载自blog.csdn.net/weixin_43160613/article/details/86524112