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

题目

image-20240325172400671

思路

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

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

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

代码

//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)

相关推荐

  1. 107. II

    2024-03-26 23:22:03       59 阅读
  2. LeetCode107. II

    2024-03-26 23:22:03       30 阅读
  3. leetcode 102.

    2024-03-26 23:22:03       48 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-03-26 23:22:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-03-26 23:22:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-03-26 23:22:03       82 阅读
  4. Python语言-面向对象

    2024-03-26 23:22:03       91 阅读

热门阅读

  1. 验证回文串

    2024-03-26 23:22:03       39 阅读
  2. 掌握大型语言模型的指南

    2024-03-26 23:22:03       43 阅读
  3. 如何解析Mysql中的binlog日志?

    2024-03-26 23:22:03       37 阅读
  4. Linux 下移植代码到ARM9 芯片需要注意的事项

    2024-03-26 23:22:03       40 阅读
  5. AI大模型学习

    2024-03-26 23:22:03       43 阅读