当前位置:网站首页>LeetCode——226. 翻转二叉树(BFS)
LeetCode——226. 翻转二叉树(BFS)
2022-06-26 17:01:00 【Always--Learning】
题目描述

解题思路
BFS是解决这个问题的核心,BFS的初始节点是一个根节点。
- 首先将根节点放入数组中。
- 取出数组中的首元素,然后交换这个元素的左右节点。
- 如果左节点存在,则将左节点加入数组中。
- 如果右节点存在,则将右节点加入数组中。
AC代码
var invertTree = function(root) {
// 使用BFS解决翻转二叉树问题
if (!root) return null;
const res = [root];
while (res.length) {
let cur = res.shift();
// 交换左右节点
[cur.left, cur.right] = [cur.right, cur.left];
if (cur.left) {
res.push(cur.left);
}
if (cur.right) {
res.push(cur.right);
}
}
return root;
};
反思
二叉树镜像和反转二叉树是一个题目,总的来说通过BFS可以高效的解决这个问题。
边栏推荐
- Technical scheme design of chain game system development - NFT chain game system development process and source code
- Platform management background and merchant menu resource management: access control design of platform management background
- NFT 交易市场社区所有化势不可挡
- SQL injection for Web Security (3)
- Daily record 2
- Over the weekend: 20000 words! Summary of JVM core knowledge, 18 serial cannons as a gift
- 物联网协议的王者:MQTT
- vue--vuerouter缓存路由组件
- [matlab project practice] prediction of remaining service life of lithium ion battery based on convolutional neural network and bidirectional long short time (cnn-lstm) fusion
- 并发之线程安全
猜你喜欢

20:第三章:开发通行证服务:3:在程序中,打通redis服务器;(仅仅是打通redis服务器,不涉及具体的业务开发)

Which low code platform is more friendly to Xiaobai? Here comes the professional evaluation!

分布式架构概述

并发之Synchronized说明

Platform management background and merchant menu resource management: merchant registration management design

Ndroid development from introduction to mastery Chapter 2: view and ViewGroup

Summary of all knowledge points of C language

玩轉Linux,輕松安裝配置MySQL

SQL injection for Web Security (3)

【推荐系统学习】推荐系统架构
随机推荐
[latex bearer] use tables in \title (error \begin doesn't match its definition.)
Deployment and operation of mongodb partitioned cluster
Redis OM . Net redis object mapping framework
7 views on NFT market prospect
并发之线程安全
Viteconfigure project path alias
The high concurrency system is easy to play, and Alibaba's new 100 million level concurrent design quick notes are really fragrant
Introduction to minimal API
Inspirational. In one year, from Xiaobai to entering the core Department of Alibaba, his counter attack
Teach you to learn dapr - 2 Must know concept
The texstudio official website cannot be opened
Sandboxed container: container or virtual machine
Memory partition model
Redis and database data consistency
Discussion: the next generation of stable coins
Find out the maximum value of each column element of NxN matrix and store it in the one-dimensional array indicated by formal parameter B in order
No manual prior is required! HKU & Tongji & lunarai & Kuangshi proposed self supervised visual representation learning based on semantic grouping, which significantly improved the tasks of target dete
一起备战蓝桥杯与CCF-CSP之大模拟炉石传说
【MATLAB项目实战】基于卷积神经网络与双向长短时(CNN-LSTM)融合的锂离子电池剩余使用寿命预测
【uniapp】uniapp手机端使用uni.navigateBack失效问题解决