当前位置:网站首页>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也是一道很经典的题
边栏推荐
- 腾讯安全联合毕马威发布监管科技白皮书,解析“3+3”热点应用场景
- 数字信号处理——线性相位型(Ⅱ、Ⅳ型)FIR滤波器设计(2)
- [brain opening] west tide and going to the world series
- How to use opcache, an optimization acceleration component of PHP
- [106] 360 check font - check whether the copyright of local Fonts is commercially available
- 華為面試題: 招聘
- JPA and criteria API - select only specific columns - JPA & criteria API - select only specific columns
- What are the PHP FPM configuration parameters
- Mobile note application
- ASP.NET Core 6 从入门到企业级实战开发应用技术汇总
猜你喜欢

redis探索之缓存击穿、缓存雪崩、缓存穿透

【datawhale202206】pyTorch推荐系统:召回模型 DSSM&YoutubeDNN

【datawhale202206】pyTorch推荐系统:多任务学习 ESMM&MMOE

Onenet Internet of things platform - mqtt product devices send messages to message queues MQ

【datawhale202206】pyTorch推荐系统:精排模型 DeepFM&DIN
![[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn](/img/f2/7931952b832e84d7b8f2615906f33f.png)
[datawhale202206] pytorch recommendation system: recall model DSSM & youtubednn
![[some notes]](/img/91/7657f90b50f012736579b1585b4ade.jpg)
[some notes]

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

How to install php7 and perform performance test using yum

BIM and safety in road maintenance-buildSmart Spain
随机推荐
手机便签应用
Double linked list related operations
2022-06-28-06-29
華為面試題: 招聘
Machine learning - Data Science Library Day 3 - Notes
Eurake分区理解
系统测试UI测试总结与问题(面试)
Question d'entrevue de Huawei: recrutement
[Yunju entrepreneurial foundation notes] Chapter 7 Entrepreneurial Resource test 5
QT 播放器之列表[通俗易懂]
ASTM D 3801固体塑料垂直燃烧试验
硬阈值(Hard Thresholding)函数解读[通俗易懂]
GID: open vision proposes a comprehensive detection model knowledge distillation | CVPR 2021
MySQL workbench data modeling function
[20211129] configuration du serveur distant du carnet de notes jupyter
Huawei interview question: Recruitment
Machine learning - Data Science Library - day two
Chapter 14 signals (IV) - examples of multi process tasks
Relationship between accuracy factor (DOP) and covariance in GPS data (reference link)
Interpretation of hard threshold function [easy to understand]