当前位置:网站首页>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可以高效的解决这个问题。
边栏推荐
- Redis 概述整理
- Redis overview
- Ndroid development from introduction to mastery Chapter 2: view and ViewGroup
- R329 (maix-ii-a (M2A) data summary
- Calculate the average of N numbers in the index group of X, and return the number that is less than the average and closest to the average through formal parameters
- Use the array to calculate the average of N numbers, and output the numbers greater than the average
- Calculate a=1, a2=1/1=a1
- Getting started with mongodb
- 20: Chapter 3: develop the pass service: 3: get through the redis server in the program; (it only connects with the redis server and does not involve specific business development)
- Demonstrate to Xiaobai the case of sub database and sub table
猜你喜欢

What is the difference between digital collections and NFT

Alibaba's "high concurrency" tutorial "basic + actual combat + source code + interview + Architecture" is a god class

Romance of the Three Kingdoms: responsibility chain model

Teach you to learn dapr - 1 The era of net developers

Leetcode 1170. Frequency of occurrence of the minimum letter of the comparison string (yes, solved)

Programmer's essential toolkit, please collect!

并发之Synchronized说明

Microservice architecture practice: business management background and SSO design, SSO client design

Don't believe it, 98% of programmers are like this

Deployment and operation of mongodb partitioned cluster
随机推荐
proxy
Decentralized NFT transaction protocol will defeat opensea
一起备战蓝桥杯与CCF-CSP之大模拟炉石传说
Concurrent thread safety
Demonstrate to Xiaobai the case of sub database and sub table
NFT 交易市场社区所有化势不可挡
10 cloud security best practices that enterprises need to know
Cache breakdown! Don't even know how to write code???
Programmer's essential toolkit, please collect!
Programmer interview guide - self introduction
MySQL index
Don't believe it, 98% of programmers are like this
Teach you to learn dapr - 9 Observability
The latest masterpiece of Alibaba, which took 182 days to produce 1015 pages of distributed full stack manual, is so delicious
Swap two numbers
The texstudio official website cannot be opened
Army chat -- registration of Registration Center
Teach you to learn dapr - 4 Service invocation
Deployment and operation of mongodb partitioned cluster
What is the difference between digital collections and NFT