对称二叉树

题目描述

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

思路:

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

 

 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

 

转载于:https://www.cnblogs.com/yuling-chao/p/7325169.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值