对称的二叉树(二叉树的镜像操作)

来源:互联网 发布:智联招聘java简历模板 编辑:程序博客网 时间:2024/06/10 19:37

题目描述

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


判断二叉树的对称性,就是把左右子树对应位置的元素进行判断是否相同,如果相同,返回False,否则,返回True

如果说二叉树本身为空,也返回False

本题与二叉树的镜像(链接)极其相似,思路可以说基本上相同。

# -*- coding:utf-8 -*-# class TreeNode:#     def __init__(self, x):#         self.val = x#         self.left = None#         self.right = Noneclass Solution:    def isSymmetrical(self, pRoot):        # write code here        if not pRoot:        return True                def IsTrue(p, q):        if not p and not q:        return True        if not p or not q:        return False        if p.val != q.val:        return False        return IsTrue(p.right, q.left) and IsTrue(p.left, q.right)        return IsTrue(pRoot.right, pRoot.left)

0 0
原创粉丝点击