题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
题目地址
思路
判断一棵二叉树是不是对称的,等价于判断其左右子树是不是镜像对称的。判断镜像对称即判断对称位置上的元素是不是相等的。
两个结点AB对称等价于:
两个结点值相等
结点A的左子树和结点B的右子树对称
结点A的右子树和结点B的左子树对称
Python
# -*- coding:utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None node1 = TreeNode(1) node2 = TreeNode(2) node3 = TreeNode(2) node4 = TreeNode(4) node5 = TreeNode(5) node6 = TreeNode(5) node7 = TreeNode(4) node1.left = node2 node1.right = node3 node2.left = node4 node2.right = node5 node3.left = node6 node3.right = node7 class Solution: def isSymmetrical(self, pRoot): # write code here if not pRoot: return True return self.judge(pRoot.left, pRoot.right) def judge(self, l, r): if not l and not r: return True if l and r and l.val == r.val: return self.judge(l.left,r.right) and self.judge(l.right,r.left) return False if __name__ == '__main__': result = Solution().isSymmetrical(node1) print(result)
作者:huangqiancun
出处:http://www.cnblogs.com/huangqiancun/
本博客若无特殊说明则由作者原创发布,欢迎转载,但请注明出处 :)