【刷爆力扣之二叉树】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;
}
相关推荐
smj2302_796826522 小时前
解决leetcode第3801题合并有序列表的最小成本
数据结构·python·算法·leetcode
栗少2 小时前
英语自学手册:系统化进阶指南基于《英语自学手册》的方法论与行动路径
人工智能·算法
Xの哲學3 小时前
深入解析 Linux systemd: 现代初始化系统的设计与实现
linux·服务器·网络·算法·边缘计算
sinat_255487813 小时前
InputStream/OutputStream小讲堂
java·数据结构·算法
cici158744 小时前
基于GPRMAX的地下管线正演模拟与MATLAB实现
开发语言·算法·matlab
副露のmagic4 小时前
更弱智的算法学习 day16
数据结构·学习·算法
DeepVis Research4 小时前
【Storage/Signal】2026年度非线性存储一致性与跨时域信号处理基准索引 (Benchmark Index)
算法·网络安全·数据集·分布式系统
liliangcsdn4 小时前
VAE中Encoder和Decoder的理论基础的探索
人工智能·算法·机器学习
Love Song残响4 小时前
30字高效MATLAB优化指南
数据结构·算法
sin_hielo5 小时前
leetcode 1975
数据结构·算法·leetcode