当前位置:网站首页>【leetcode】107.二叉树的层序遍历II
【leetcode】107.二叉树的层序遍历II
2022-04-23 10:27:00 【前端corner】
题目
给你二叉树的根节点 root ,返回其节点值 自底向上的层序遍历 。 (即按从叶子节点所在层到根节点所在的层,逐层从左向右遍历)
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[15,7],[9,20],[3]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
树中节点数目在范围 [0, 2000] 内
-1000 <= Node.val <= 1000
思路

- 想想这道题目和这一道【leetcode】102.二叉树的层序遍历题目遍历结果会有什么区别呢?其实就是那道题目结果数组翻转一下就行了。
- 翻转的操作可以在往结果数组里添加单层遍历结果时进行,即从数组头部添加。
代码

/** * Definition for a binary tree node. * function TreeNode(val, left, right) { * this.val = (val===undefined ? 0 : val) * this.left = (left===undefined ? null : left) * this.right = (right===undefined ? null : right) * } */
/** * @param {TreeNode} root * @return {number[][]} */
var levelOrderBottom = function(root) {
if(!root) return []
let queue = [root]
let res = []
while(queue.length){
const len = queue.length
let curLevel = [] //存放每一层的节点
for(let i = 0 ; i < len ; i++){
const curNode = queue.shift()
curLevel.push(curNode.val)
if(curNode.left) queue.push(curNode.left)
if(curNode.right) queue.push(curNode.right)
}
res.unshift(curLevel) //存放当层遍历结果,从数组头部添加
}
return res
};
复杂度
- 时间复杂度: O ( n ) O(n) O(n)
- 空间复杂度: O ( n ) O(n) O(n)
关注我的专栏,每天更新三道leetcode题解,一起变强!
版权声明
本文为[前端corner]所创,转载请带上原文链接,感谢
https://blog.csdn.net/laplacepoisson/article/details/124359081
边栏推荐
- SQL Server 递归查询上下级
- 链表相交(链表)
- Juc并发编程07——公平锁真的公平吗(源码剖析)
- 2022 mobile crane driver test question bank simulation test platform operation
- DBA common SQL statements (5) - latch related
- 59、螺旋矩阵(数组)
- Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
- Question bank and answers of Shanghai safety officer C certificate examination in 2022
- 微信小程序简介、发展史、小程序的优点、申请账号、开发工具、初识wxml文件和wxss文件
- 域名和IP地址的联系
猜你喜欢

Swagger2 接口如何导入Postman

mysql同一个表中相同数据怎么合并
MapReduce core and foundation demo

Example of pop-up task progress bar function based on pyqt5

Sim Api User Guide(6)

Question bank and answers of Shanghai safety officer C certificate examination in 2022

Juc并发编程09——Condition实现源码分析

Juc并发编程07——公平锁真的公平吗(源码剖析)

Exercise questions and simulation test of refrigeration and air conditioning equipment operation test in 2022

MapReduce compression
随机推荐
第一章 Oracle Database In-Memory 相关概念(IM-1.1)
What about Jerry's stack overflow? [chapter]
Chapter 2 Oracle database in memory architecture (I) (im-2.1)
Sim Api User Guide(7)
转:毛姆:阅读是一座随身携带的避难所
mysql同一个表中相同数据怎么合并
深度选择器
206. Reverse linked list (linked list)
997. Square of ordered array (array)
C#和数据库连接中类的问题
202. Happy number
Sim Api User Guide(5)
Jinglianwen technology - professional data annotation company and intelligent data annotation platform
Swagger2 接口如何导入Postman
59. Spiral matrix (array)
242. Valid Letter ectopic words (hash table)
/etc/shadow可以破解吗?
19. Delete the penultimate node of the linked list (linked list)
Jerry's users how to handle events in the simplest way [chapter]
101. Symmetric Tree
