当前位置:网站首页>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也是一道很经典的题
边栏推荐
- R语言基于h2o包构建二分类模型:使用h2o.gbm构建梯度提升机模型GBM、使用h2o.auc计算模型的AUC值
- ANSI/UL 94 VTM薄质材料垂直燃烧测试
- Good luck brought by years of persistence
- 循环链表--
- [datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE
- Circular linked list--
- Ansible相关内容梳理
- CPI tutorial - asynchronous interface creation and use
- GPS 数据中的精度因子(DOP)与协方差之间的关系 (参考链接)
- ASTM D 3801 vertical burning test of solid plastics
猜你喜欢

《MATLAB 神经网络43个案例分析》:第40章 动态神经网络时间序列预测研究——基于MATLAB的NARX实现

BIM and safety in road maintenance-buildSmart Spain

本科毕业四年:工作,辞职,结婚,买房

【datawhale202206】pyTorch推荐系统:精排模型 DeepFM&DIN

Switch basic experiment

2022-06-28-06-29

Indefinite integral

使用nvm管理nodejs(把高版本降级为低版本)

Sort out relevant contents of ansible

Chained storage of queues
随机推荐
本科毕业四年:工作,辞职,结婚,买房
Onenet Internet of things platform - create mqtts products and devices
Need your own cognition
[datawhale202206] pytorch recommendation system: precision model deepfm & DIN
[datawhale202206] pytorch recommendation system: multi task learning esmm & MMOE
Nc100 converts strings to integers (ATOI)
Indefinite integral
[brain opening] west tide and going to the world series
6.30 simulation summary
Zero copy technology of MySQL
QT 播放器之列表[通俗易懂]
MySQL common functions
[Yu Yue education] financial management reference materials of Ningbo University of Finance and Economics
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 8
"Analysis of 43 cases of MATLAB neural network": Chapter 40 research on prediction of dynamic neural network time series -- implementation of NARX based on MATLAB
基因检测,如何帮助患者对抗疾病?
循环链表--
Mysql database knowledge collation
Virtualenv+pipenv virtual environment management
下半年还有很多事要做