当前位置:网站首页>[牛客网刷题 Day6] JZ27 二叉树的镜像
[牛客网刷题 Day6] JZ27 二叉树的镜像
2022-07-07 08:14:00 【strawberry47】
题目:
操作给定的二叉树,将其变换为源二叉树的镜像。
思路
返回的是一棵树,那得建立TreeNode吧,想到了两种方法:
① 使用队列,从右往左存node,这样读出来的顺序就是镜像的;可是答案要求输出一颗树,我不知道怎么转换成树
② 使用递归,当孩子为叶节点时,交换左右节点的位置;可是还是写不来,o(╥﹏╥)o
偷偷看了答案,用堆栈存储节点,每次取出来就交换左右节点,于是照着这个思路写了一下代码:
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param pRoot TreeNode类
# @return TreeNode类
#
class Solution:
def Mirror(self , pRoot: TreeNode) -> TreeNode:
# write code here
if pRoot is None:
return None
q = []
q.append(pRoot)
while len(q):
for i in range(len(q)):
node = q.pop()
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
# swap
tmp = node.left
node.left = node.right
node.right = tmp
return pRoot
答案:
看了看递归:
解题步骤:
1、特判:如果pRoot为空,返回空
2、交换左右子树
3、把pRoot的左子树放到Mirror中镜像一下
4、把pRoot的右子树放到Mirror中镜像一下
5、返回根节点root
class Solution:
def Mirror(self , pRoot ):
# write code here
if not pRoot:
return pRoot
# 左右子树交换
pRoot.left, pRoot.right = pRoot.right, pRoot.left
# 递归左右子树
self.Mirror(pRoot.left)
self.Mirror(pRoot.right)
return pRoot
网上搜了一下递归的解法:
解决递归问题一般就三步曲,分别是:
第一步,定义函数功能 -> 翻转树
第二步,寻找递归终止条件 -> 已经是叶节点了or已经为空了
第二步,递推函数的等价关系式 -> 翻转node的左子树和右子树
边栏推荐
- 浅谈日志中的返回格式封装格式处理,异常处理
- 2022.7.6DAY598
- [email protected] can help us get the log object quickly
- 1324:【例6.6】整数区间
- ES6中的原型对象
- Programming features of ISP, IAP, ICP, JTAG and SWD
- 根据设备信息进行页面跳转至移动端页面或者PC端页面
- Yarn的基础介绍以及job的提交流程
- Video based full link Intelligent Cloud? This article explains in detail what Alibaba cloud video cloud "intelligent media production" is
- Some thoughts on the testing work in the process of R & D
猜你喜欢

Postman interface test II

XML配置文件解析与建模

0x0fa23729 (vcruntime140d.dll) (in classes and objects - encapsulation.Exe) exception thrown (resolved)

mysql插入数据创建触发器填充uuid字段值

【acwing】786. 第k个数

Weekly recommended short videos: what are the functions of L2 that we often use in daily life?

Methods of adding centerlines and centerlines in SolidWorks drawings

【二开】【JeecgBoot】修改分页参数

The variables or functions declared in the header file cannot be recognized after importing other people's projects and adding the header file

SQLyog数据库怎么取消自动保存更改
随机推荐
Use the fetch statement to obtain the repetition of the last row of cursor data
php \n 换行无法输出
Factorial implementation of large integer classes
EasyExcel读取写入简单使用
Inno setup packaging and signing Guide
. Net configuration system
嵌入式背景知识-芯片
SQLyog数据库怎么取消自动保存更改
C#记录日志方法
IPv4 socket address structure
ORM model -- creation and query of data records
XML configuration file parsing and modeling
Advanced function learning in ES6
根据设备信息进行页面跳转至移动端页面或者PC端页面
@Configuration, use, principle and precautions of transmission:
Embedded background - chip
The story of Plato and his three disciples: how to find happiness? How to find the ideal partner?
对存储过程进行加密和解密(SQL 2008/SQL 2012)
1324:【例6.6】整数区间
Postman tutorial - scripting