Python:对称的二叉树

来源:互联网 发布:如何选购家具 知乎 编辑:程序博客网 时间:2024/06/05 02:16


牛客网上的剑指 offer的在线编程:

题目描述

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
class TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass 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 not pRoot.left and pRoot.right:            return False        if pRoot.left and not pRoot.right:            return False        return is_same(pRoot.left, pRoot.right)


原创粉丝点击