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)
相关推荐
毕业设计制作和分享31 分钟前
springboot150基于springboot的贸易行业crm系统
java·vue.js·spring boot·后端·毕业设计·mybatis
电子_咸鱼3 小时前
LeetCode——Hot 100【电话号码的字母组合】
数据结构·算法·leetcode·链表·职场和发展·贪心算法·深度优先
仰泳的熊猫3 小时前
LeetCode:785. 判断二分图
数据结构·c++·算法·leetcode
rit84324993 小时前
基于MATLAB实现基于距离的离群点检测算法
人工智能·算法·matlab
my rainy days6 小时前
C++:友元
开发语言·c++·算法
haoly19896 小时前
数据结构和算法篇-归并排序的两个视角-迭代和递归
数据结构·算法·归并排序
微笑尅乐6 小时前
中点为根——力扣108.讲有序数组转换为二叉搜索树
算法·leetcode·职场和发展
小梁努力敲代码6 小时前
java数据结构--List的介绍
java·开发语言·数据结构
摸鱼的老谭6 小时前
构建Agent该选Python还是Java ?
java·python·agent
lang201509286 小时前
Spring Boot 官方文档精解:构建与依赖管理
java·spring boot·后端