题目描述

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

思路:

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

 

 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 True
11         if (pRoot.left and not pRoot.right) or (not pRoot.left and pRoot.right):
12             return False
13         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 True
19         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

 

posted on 2017-08-09 14:39  刀刀121  阅读(82)  评论(0编辑  收藏  举报