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

题目

思路

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

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

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

代码

java 复制代码
//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>();
        //创建一个结果List
        List<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)
相关推荐
oioihoii几秒前
深入理解 C++ 现代类型推导:从 auto 到 decltype 与完美转发
java·开发语言·c++
papership7 分钟前
【入门级-算法-5、数值处理算法:高精度的减法】
算法·1024程序员节
lingran__11 分钟前
算法沉淀第十天(牛客2025秋季算法编程训练联赛2-基础组 和 奇怪的电梯)
c++·算法
韩立学长18 分钟前
【开题答辩实录分享】以《租房小程序的设计和实现》为例进行答辩实录分享
java·spring boot·小程序
zl97989922 分钟前
SpringBoot-数据访问之MyBatis与Redis
java·spring boot·spring
DuHz22 分钟前
基于MIMO FMCW雷达的二维角度分析多径抑制技术——论文阅读
论文阅读·物联网·算法·信息与通信·毫米波雷达
K_i13430 分钟前
Tomcat核心原理与运维实战指南
java·运维·tomcat
Dragon_D.1 小时前
排序算法大全——插入排序
算法·排序算法·c·学习方法
重生之我是Java开发战士1 小时前
【Java EE】快速上手Spring Boot
java·spring boot·java-ee
從南走到北1 小时前
JAVA国际版一对一视频交友视频聊天系统源码支持H5 + APP
java·微信·微信小程序·小程序·音视频·交友