【刷爆力扣之二叉树】107. 二叉树的层序遍历 II

107. 二叉树的层序遍历 II

这道题要求进行自底向上的层序遍历 ,可以先使用正序层序遍历的方式对树进行遍历,然后将每一层的遍历结果放入一个栈数据结构中 ,等遍历完成后,将栈数据结构中的每一层的节点再弹出加入到结果集合,即可将原先栈中的数据顺序反转,实现自底向上的层序遍历

java 复制代码
public List<List<Integer>> levelOrderBottom(TreeNode root) {
    List<List<Integer>> res = new ArrayList<>();
    // 栈数据结构暂存数据
    Stack<List<Integer>> stack = new Stack<>();
    if (root == null) {
        return res;
    }
    // 正常的层序遍历,并将结果放入栈数据结构
    Queue<TreeNode> queue = new LinkedList<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        List<Integer> level = new ArrayList<>();
        int size = queue.size();
        for (int i = 0; i < size; i++) {
            TreeNode polled = queue.poll();
            level.add(polled.val);
            if (polled.left != null) {
                queue.offer(polled.left);
            }
            if (polled.right != null) {
                queue.offer(polled.right);
            }
        }
        stack.push(level);
    }
    // 将栈中的数据弹出加入结果集合,实现顺序反转
    while (!stack.isEmpty()){
        res.add(stack.pop());
    }
    return res;
}
相关推荐
yugi9878385 分钟前
基于MATLAB实现协同过滤电影推荐系统
算法·matlab
TimberWill5 分钟前
哈希-02-最长连续序列
算法·leetcode·排序算法
Morwit23 分钟前
【力扣hot100】64. 最小路径和
c++·算法·leetcode
leoufung23 分钟前
LeetCode 373. Find K Pairs with Smallest Sums:从暴力到堆优化的完整思路与踩坑
java·算法·leetcode
wifi chicken1 小时前
数组遍历求值,行遍历和列遍历谁更快
c语言·数据结构·算法
胡楚昊1 小时前
NSSCTF动调题包通关
开发语言·javascript·算法
Gold_Dino2 小时前
agc011_e 题解
算法
bubiyoushang8882 小时前
基于蚁群算法的直流电机PID参数整定 MATLAB 实现
数据结构·算法·matlab
风筝在晴天搁浅2 小时前
hot100 240.搜索二维矩阵Ⅱ
算法·矩阵
girl-07262 小时前
2025.12.24代码分析
算法