当前位置: 首页 > news >正文

leetcode 107.二叉树的层序遍历II

题目

image-20240325172400671

思路

正常层序遍历输出: [[3],[9,20],[15,7]]

这道题要求的输出:[[15,7],[9,20],[3]]

可以观察到,只要我们把原来的结果reverse一下就行了。

代码

//leetcode submit region begin(Prohibit modification and deletion)import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;/*** Definition for a binary tree node.* public class TreeNode {* int val;* TreeNode left;* TreeNode right;* TreeNode() {}* TreeNode(int val) { this.val = val; }* TreeNode(int val, TreeNode left, TreeNode right) {* this.val = val;* this.left = left;* this.right = right;* }* }*/
class Solution {public List<List<Integer>> levelOrderBottom(TreeNode root) {//创建一个辅助队列,存放节点Queue<TreeNode> queue = new LinkedList<TreeNode>();//创建一个结果ListList<List<Integer>> res = new ArrayList<>();if (root == null) {return res;}queue.add(root);while (!queue.isEmpty()) {int len = queue.size();List<Integer> item = new ArrayList<>();while (len > 0) {TreeNode temp = queue.poll();item.add(temp.val);if (temp.left != null)queue.add(temp.left);if (temp.right != null)queue.add(temp.right);len--;}res.add(item);}Collections.reverse(res);return res;}
}
//leetcode submit region end(Prohibit modification and deletion)
http://www.lryc.cn/news/325951.html

相关文章:

  • Java生成唯一ID的方式有哪些?
  • 代码随想录day44:动态规划over,回文子串及字序列
  • ElasticSearch启动报错:Exception in thread “main“ SettingsException
  • git配置密钥
  • Pandas库常用方法、函数集合
  • Qt实现TFTP Server和 TFTP Client(一)
  • MySQL数据库的日志管理以及备份和恢复
  • Maven发布开源框架到远程仓库
  • Qt创建窗口选择的三个父类介绍 ----- QWidget、QMainWindow、QDialog
  • 论文翻译 - Defending Against Alignment-Breaking Attacks via Robustly Aligned LLM
  • Kafka总结问题
  • 【RPG Maker MV 仿新仙剑 战斗场景UI (八)】
  • 【PyQt】18 -菜单等顶层操作
  • 线性代数基础概念和在AI中的应用
  • elasticsearch _cat/indices docs.count is different than <index>/_count
  • 关系型数据库mysql(7)sql高级语句
  • 计算机网络——网络基础1
  • ERDUnet: An Efficient Residual Double-codingUnet for Medical Image Segmentation
  • vue响应式基础
  • 每天上万简历,录取不到1%!阿里腾讯的 offer 都给了哪些人?
  • 外包干了20天,技术退步明显.......
  • 4核8G云服务器,阿里云要多少钱?
  • 数学分析复习:振荡型级数的收敛判别
  • 阿里CICD流水线Docker部署,将阿里镜像私仓中的镜像部署到服务器中
  • 并发VS并行
  • C语言经典例题(8) --- 进制A+B、网购、及格分数、最高分数、计算一元二次方程
  • 两区域二次调频风火机组,麻雀启发式算法改进simulink与matlab联合
  • 自动驾驶国际标准ISO文件
  • 【数据结构】双向奔赴的爱恋 --- 双向链表
  • 【Redis】高频面试题