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)
相关推荐
祈祷苍天赐我java之术5 小时前
Linux 进阶之性能调优,文件管理,网络安全
java·linux·运维
无处不在的海贼5 小时前
小明的Java面试奇遇之发票系统相关深度实战挑战
java·经验分享·面试
武子康5 小时前
Java-109 深入浅出 MySQL MHA主从故障切换机制详解 高可用终极方案
java·数据库·后端·mysql·性能优化·架构·系统架构
秋难降6 小时前
代码界的 “建筑师”:建造者模式,让复杂对象构建井然有序
java·后端·设计模式
mit6.8246 小时前
8.27 网格memo
c++·算法
jeffery8926 小时前
4056:【GESP2403八级】接竹竿
数据结构·c++·算法
BillKu6 小时前
Spring Boot 多环境配置
java·spring boot·后端
Ghost-Face7 小时前
图论基础
算法
默归7 小时前
分治法——二分答案
python·算法
君不见,青丝成雪8 小时前
SpringBoot项目占用内存优化
java·spring boot·后端