Python对称的二叉树多种思路实现方法
作者:雾行 时间:2022-09-12 17:27:10
对称二叉树的含义非常容易理解,左右子树关于根节点对称,具体来讲,对于一颗对称二叉树的每一颗子树,以穿过根节点的直线为对称轴,左边子树的左节点=右边子树的右节点,左边子树的右节点=左边子树的左节点。所以对称二叉树的定义是针对一棵树,而判断的操作是针对节点,这时可以采取由上到下的顺序,从根节点依次向下判断,只需要重复调用函数,不需要回溯。
题目:对称的二叉树题:
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的
解题思路一:先遍历右子节点再遍历左子节点。注意,我们必须把遍历二叉树时遇到的空指针考虑进来。
class Solution:
def isSymmetrical(self, pRoot):
# write code here
return self.isSymmetricalCore(pRoot,pRoot)
def isSymmetricalCore(self,pRoot1,pRoot2):
if not pRoot1 and not pRoot2:
return True
if not pRoot1 or not pRoot2:
return False
if pRoot1.val != pRoot2.val:
return False
return self.isSymmetricalCore(pRoot1.left,pRoot2.right) and self.isSymmetricalCore(pRoot1.right,pRoot2.left)
解题思路二:迭代
def isSymmetric(self, root: 'TreeNode') -> 'bool':
stack = root and [(root.left, root.right)]
while stack:
p1, p2 = stack.pop()
if not p1 and not p2: continue
if not p1 or not p2: return False
if p1.val != p2.val: return False
stack.append((p1.left, p2.right))
stack.append((p1.right, p2.left))
return True
来源:https://blog.csdn.net/weixin_44151089/article/details/104471349
标签:Python,对称二叉树
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
pytorch实践线性模型3d详解
2023-04-01 22:58:29
![](https://img.aspxhome.com/file/2023/7/115177_0s.png)
python采集博客中上传的QQ截图文件
2021-03-03 16:45:25
Python3 执行Linux Bash命令的方法
2023-11-03 06:47:15
python数据处理之Pandas类型转换的实现
2021-04-11 11:17:36
![](https://img.aspxhome.com/file/2023/4/65864_0s.png)
使用Python操作excel文件的实例代码
2023-07-14 10:45:50
gem install mysql报错checking for mysql_qu
2010-11-11 12:13:00
在SQL Server中使用SQL语句查询一个存储过程被其它所有的存储过程引用的存储过程名
2012-07-11 16:09:40
MySQL的数据库常用命令 超级实用版分享
2012-01-05 18:58:00
使用Fabric自动化部署Django项目的实现
2022-09-05 22:00:33
网页效果图设计之色彩索引
2008-03-23 13:53:00
![](https://img.aspxhome.com/file/UploadPic/up/2008032314313926.gif)
Python直接赋值与浅拷贝和深拷贝实例讲解使用
2021-06-16 08:21:21
![](https://img.aspxhome.com/file/2023/3/102323_0s.jpg)
go-cache的基本使用场景示例解析
2023-08-06 00:52:02
Python定义一个跨越多行的字符串的多种方法小结
2022-08-04 03:34:27
![](https://img.aspxhome.com/file/2023/0/115070_0s.jpg)
python+opencv实现文字颜色识别与标定功能
2023-09-05 02:25:27
![](https://img.aspxhome.com/file/2023/2/110012_0s.png)
基于Python创建可定制的HTTP服务器
2023-08-09 22:46:09
![](https://img.aspxhome.com/file/2023/0/93540_0s.png)
关于Python中request发送post请求传递json参数的问题
2022-12-23 06:20:33
![](https://img.aspxhome.com/file/2023/8/104398_0s.png)
发布你的Python模块详解
2021-06-10 02:03:53
Python+Pygame实现怀旧游戏飞机大战
2023-09-27 03:36:52
查看ASP详细错误提示信息的图文设置方法
2011-02-05 11:02:00
![](https://img.aspxhome.com/file/UploadPic/20112/5/20112511339472s.jpg)
asp如何创建一个功能强大的文档管理程序?
2009-11-15 17:44:00