当前位置:网站首页>leetcode:226. 翻转二叉树【dfs翻转】
leetcode:226. 翻转二叉树【dfs翻转】
2022-07-01 12:35:00 【白速龙王的回眸】

分析
dfs返回这个子树反转后的结果
如果是叶子节点就返回自己
如果有左孩子,右孩子就变成反转后的左孩子
如果有右孩子,左孩子就变成反转后的右孩子
然后要用temp中间记录一下,不能边改边dfs
temp初值为None即可
ac code
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
if not root:
return root
def dfs(node):
if node.left is None and node.right is None:
return node
temp1 = temp2 = None
if node.left:
temp1 = dfs(node.left)
if node.right:
temp2 = dfs(node.right)
node.right = temp1
node.left = temp2
return node
dfs(root)
return root
总结
反转二叉树用了dfs也是一道很经典的题
边栏推荐
- 【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN
- 微信小程序 – 80个实用的微信小程序项目实例
- 使用BurpSuite对app抓包教程
- ustime写出了bug
- Typora realizes automatic uploading of picture pasting
- Tencent Li Wei: deeply cultivate "regulatory technology" to escort the steady and long-term development of the digital economy
- GID:旷视提出全方位的检测模型知识蒸馏 | CVPR 2021
- Machine learning - Data Science Library - day two
- 《MATLAB 神经网络43个案例分析》:第40章 动态神经网络时间序列预测研究——基于MATLAB的NARX实现
- AI抠图工具
猜你喜欢

Onenet Internet of things platform - create mqtts products and devices

【20211129】Jupyter Notebook远程服务器配置

手机便签应用
![[datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE](/img/8f/64fea641730795a2b5252cc2c8cdd2.png)
[datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE

数论基础及其代码实现
![[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 5](/img/f5/9c68b3dc30362d3776c262fdc13fd0.jpg)
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 5
![[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn](/img/f2/7931952b832e84d7b8f2615906f33f.png)
[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn

第十四章 信号(四)- 多进程任务示例

Share several tools for designing exquisite circuit diagrams

Arm GIC (V) how arm TrustZone supports security interrupt analysis notes.
随机推荐
List of QT players [easy to understand]
被锡膏坑了一把
Onenet Internet of things platform - mqtt product devices send messages to message queues MQ
MySQL common functions
手把手教你完成图像分类实战——基于卷积神经网络的图像识别
Fatal error: execution: there is no such file or directory
Ansi/ul 94 VTM vertical burning test for thin materials
Interpretation of hard threshold function [easy to understand]
First intention is the most important
[brain opening] west tide and going to the world series
ustime写出了bug
JS related interview questions and answers (1)
下半年还有很多事要做
Ipv6-6to4 experiment
IOS interview
What are the PHP FPM configuration parameters
BIM and safety in road maintenance-buildSmart Spain
Good luck brought by years of persistence
Queue operation---
GPS 数据中的精度因子(DOP)与协方差之间的关系 (参考链接)