当前位置:网站首页>【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
边栏推荐
- Common SQL statements of DBA (6) - daily management
- 使用IDEA开发Spark程序
- Realizing data value through streaming data integration (5) - flow analysis
- 101. Symmetric Tree
- What are Jerry's usual program exceptions? [chapter]
- Define linked list (linked list)
- 利用多线程按顺序连续输出abc10次
- CentOS/Linux安装MySQL
- C#和数据库连接中类的问题
- Chapter I Oracle database in memory related concepts (Continued) (im-1.2)
猜你喜欢
Sim Api User Guide(6)
Depth selector
中职网络安全2022国赛之CVE-2019-0708漏洞利用
Jerry's more accurate determination of abnormal address [chapter]
解决VMware卸载后再安装出现的问题
Sim Api User Guide(5)
Shell script interaction free
Examination questions and answers of the third batch (main person in charge) of Guangdong safety officer a certificate in 2022
Sim Api User Guide(6)
【无标题】
随机推荐
Zhengda international explains what the Dow Jones industrial index is?
DBA common SQL statements (5) - latch related
Common DBA SQL statements (4) - Top SQL
SQL Server 递归查询上下级
lnmp的配置
Common SQL statements of DBA (6) - daily management
解决方案架构师的小锦囊 - 架构图的 5 种类型
206. Reverse linked list (linked list)
Realizing data value through streaming data integration (5) - flow analysis
第三章 启用和调整IM列存储的大小(IM-3.1)
【省选联考 2022 D2T1】卡牌(状态压缩 DP,FWT卷积)
1、两数之和(哈希表)
SQL tuning series - SQL performance methodology
142. Circular linked list||
Realizing data value through streaming data integration (4) - streaming data pipeline
142、环形链表||
Sim Api User Guide(6)
JUC concurrent programming 09 -- source code analysis of condition implementation
Leetcode22:括号生成
Realize data value through streaming data integration (2)