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)
相关推荐
labuladong5 分钟前
全新的算法 & Agent 课程页上线
算法·llm·agent
leobertlan1 小时前
好玩系列 | 以简构繁,从把玩一把天平进入信息论和编码
算法
电科_银尘2 小时前
【大模型算法与工程 48】项目实战:可调用、可追踪的大模型问答服务
算法
电科_银尘2 小时前
【大模型算法与工程 47】服务工程:并发、排队、限流与可观测性
算法
西数科技CDRSA2 小时前
BGA封装NAND芯片不识别,Flash Extractor引脚直读还原原始镜像
数据结构·算法·硬件工程
AvocadoZeroOneOI3 小时前
Kadane 算法(最大子段和)
c++·学习·算法·动态规划
持敬chijing4 小时前
JAVA与CVE漏洞4-Log4J 漏洞原理与实现
java·网络安全·log4j·系统安全·网络攻击模型·安全威胁分析
软件技术NINI4 小时前
基于SpringBoot的社区留守儿童帮扶系统
java·spring boot·后端
会编程的吕洞宾5 小时前
Spring Boot虚拟线程实战:吞吐提升3倍
java·经验分享·后端·spring