当前位置:网站首页>[牛客网刷题 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的左子树和右子树
边栏推荐
- ORM model -- associated fields, abstract model classes
- Enterprise practice | construction of banking operation and maintenance index system under complex business relations
- Parameter sniffing (2/2)
- Appx代碼簽名指南
- SQLyog数据库怎么取消自动保存更改
- 嵌入式背景知识-芯片
- Weekly recommended short videos: what are the functions of L2 that we often use in daily life?
- High number_ Chapter 1 space analytic geometry and vector algebra_ Quantity product of vectors
- 关于hzero-resource报错(groovy.lang.MissingPropertyException: No such property: weight for class)
- HAL库配置通用定时器TIM触发ADC采样,然后DMA搬运到内存空间。
猜你喜欢
每周推荐短视频:L2级有哪些我们日常中经常会用到的功能?
1324:【例6.6】整数区间
Talking about the return format in the log, encapsulation format handling, exception handling
Postman interface test III
Appx code signing Guide
STM32 ADC and DMA
[second on] [jeecgboot] modify paging parameters
STM32基础知识—内存映射
Leetcode exercise - 113 Path sum II
XML配置文件解析与建模
随机推荐
Inno Setup 打包及签名指南
Experience sharing of software designers preparing for exams
Programming features of ISP, IAP, ICP, JTAG and SWD
【acwing】789. Range of numbers (binary basis)
How to cancel automatic saving of changes in sqlyog database
Why is the reflection efficiency low?
STM32 ADC和DMA
C logging method
[second on] [jeecgboot] modify paging parameters
2022.7.4DAY596
单片机(MCU)最强科普(万字总结,值得收藏)
Leetcode exercise - 113 Path sum II
Embedded background - chip
01 use function to approximate cosine function (15 points)
串口通讯继电器-modbus通信上位机调试软件工具项目开发案例
ORM model -- associated fields, abstract model classes
Use the fetch statement to obtain the repetition of the last row of cursor data
.NET配置系统
【剑指Offer】42. 栈的压入、弹出序列
P1223 排队接水/1319:【例6.1】排队接水