首页 > 其他 > 详细

对称二叉树

时间:2017-08-09 15:03:27      阅读:237      评论:0      收藏:0      [点我收藏+]

题目描述

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

思路:

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

 

 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

 

对称二叉树

原文:http://www.cnblogs.com/yuling-chao/p/7325169.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!