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)
相关推荐
bearpping2 分钟前
怎么下载安装yarn
java
西门吹雪分身14 分钟前
JDK8之四大核心函数式接口
java·函数式接口
华科易迅25 分钟前
Spring AOP
java·后端·spring
架构师沉默28 分钟前
Gemini 正式登陆香港,不用翻墙!
java·后端·架构
njidf29 分钟前
C++中的访问者模式
开发语言·c++·算法
zihao_tom44 分钟前
Spring WebFlux:响应式编程
java·后端·spring
C_Si沉思44 分钟前
C++中的工厂模式变体
开发语言·c++·算法
一只大袋鼠1 小时前
JavaWeb ——Cookie 对象
java·servlet·javaweb·cookie·小蛋糕
C羊驼1 小时前
C语言学习笔记(十五):预处理
c语言·经验分享·笔记·学习·算法
m0_569881471 小时前
C++中的适配器模式变体
开发语言·c++·算法