当前位置:网站首页>【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
边栏推荐
- 1. Sum of two numbers (hash table)
- Comparison and practice of prototype design of knowledge service app
- 通过流式数据集成实现数据价值(2)
- 微信小程序简介、发展史、小程序的优点、申请账号、开发工具、初识wxml文件和wxss文件
- Sim Api User Guide(8)
- DBA常用SQL语句(1)— 概况信息
- 454. Sum of four numbers (hash table)
- Arm debugging (1): two methods to redirect printf to serial port in keil
- lnmp的配置
- 中职网络安全2022国赛之CVE-2019-0708漏洞利用
猜你喜欢
【无标题】
Sim Api User Guide(4)
Six practices of Windows operating system security attack and defense
0704、ansible----01
net start mysql MySQL 服务正在启动 . MySQL 服务无法启动。 服务没有报告任何错误。
得到知识服务app原型设计比较与实践
mysql同一个表中相同数据怎么合并
第120章 SQL函数 ROUND
C language - custom type
[provincial election joint examination 2022 d2t1] card (state compression DP, FWT convolution)
随机推荐
解决VMware卸载后再安装出现的问题
Leetcode22:括号生成
Configuration of LNMP
C#和数据库连接中类的问题
Turn: Maugham: reading is a portable refuge
ansible 云计算 自动化
Sim Api User Guide(6)
定义链表(链表)
209. Subarray with the smallest length (array)
Using multithreading to output abc10 times in sequence
Sim Api User Guide(7)
19. Delete the penultimate node of the linked list (linked list)
19、删除链表的倒数第N个节点(链表)
通过流式数据集成实现数据价值(2)
CSP认证 202203-2 出行计划(多种解法)
Depth selector
Reading integrity monitoring techniques for vision navigation systems - 3 background
Common SQL statements of DBA (6) - daily management
通过流式数据集成实现数据价值(1)
CentOS/Linux安装MySQL