对称二叉树

来源:互联网 发布:新型数字滤波算法 编辑:程序博客网 时间:2024/06/07 02:15
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

思路:

 根节点以及其左右子树,左子树的左子树和右子树的右子树相同,左子树的右子树和右子树的左子树相同即可,采用递归.

 

 1 # -*- coding:utf-8 -*- 2 # class TreeNode: 3 #     def __init__(self, x): 4 #         self.val = x 5 #         self.left = None 6 #         self.right = None 7 class Solution: 8     def isSymmetrical(self, pRoot):      # write code here 9         if not pRoot :10             return True11         if (pRoot.left and not pRoot.right) or (not pRoot.left and pRoot.right):12             return False13         return self.is_same(pRoot.left,pRoot.right)14 15 16     def is_same(self,p1,p2):17         if not p1 and not p2:18             return True19         if (p1 and p2) and p1.val==p2.val:20             return self.is_same(p1.left,p2.right) and self.is_same(p1.right,p2.left)21         return False

 

原创粉丝点击