当前位置:网站首页>LeetCode——226. 翻轉二叉樹(BFS)
LeetCode——226. 翻轉二叉樹(BFS)
2022-06-26 17:15: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可以高效的解决這個問題。
边栏推荐
- The texstudio official website cannot be opened
- Convert the decimal positive integer m into the number in the forward K (2 < =k < =9) system and output it in bits
- Quantitative contract system development analysis case - detailed explanation of contract quantitative system development scheme
- Redis' 43 serial cannons, try how many you can carry
- Fgetc() reads content from file
- Microservice architecture practice: business management background and SSO design: SSO design
- Find all primes less than or equal to Lim, store them in AA array, and return the number of primes
- SQL injection for Web Security (3)
- Cache breakdown! Don't even know how to write code???
- sql中ROUND和TRUNCATE的区别(四舍五入还是截取小数点后几位)
猜你喜欢

一起备战蓝桥杯与CCF-CSP之大模拟炉石传说

10 cloud security best practices that enterprises need to know

Platform management background and merchant menu resource management: access control design of platform management background

Deployment and operation of mongodb partitioned cluster

直播预告|程序员进击,如何提升研发效能?6月21日晚视频号、B站同步直播,不见不散!

Basic requirements: 7 problems in singleton mode

Discover K8E: minimalist kubernetes distribution

Army chat -- registration of Registration Center

NFT 交易市场社区所有化势不可挡

Concurrent thread safety
随机推荐
Toupper function
sparksql如何通过日期返回具体周几-dayofweek函数
Environment setup mongodb
Record the use process of fenics
Use middleware to record slow laravel requests
Discover K8E: minimalist kubernetes distribution
Wechat app mall, review products, upload commodity pictures, and score Commodity Services
[recommendation system learning] recommendation system architecture
Concurrent thread safety
C language -- legal identifier and integer
Some explanations for latex CJK
[Error] ld returned 1 exit status
Technical scheme design of chain game system development - NFT chain game system development process and source code
The texstudio official website cannot be opened
Getting started with mongodb
Teach you to learn dapr - 4 Service invocation
NFT 交易市场社区所有化势不可挡
Discussion: the next generation of stable coins
进军AR领域,这一次罗永浩能成吗?
The student record consists of student number and academic performance. The data of n students have been stored in the a structure array to find out the student record with the lowest performance