【刷爆力扣之二叉树】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;
}
相关推荐
foundbug99912 分钟前
自适应滤除直达波干扰的MATLAB实现
开发语言·算法·matlab
CN-Dust2 小时前
【C++】while语句例题专题
数据结构·c++·算法
灵智实验室2 小时前
PX4位置速度估计技术详解(四):LPE 激光雷达高度融合的实现错误
算法·无人机·px 4
CQU_JIAKE2 小时前
【A】3742,3387,并查集
算法
gihigo19982 小时前
CHAN时延估计算法(二维/三维定位实现)
算法
freexyn3 小时前
Matlab自学笔记七十六:表达式的展开、因式分解、化简、合并同类项
笔记·算法·matlab
样例过了就是过了3 小时前
LeetCode热题 不同路径
c++·算法·leetcode·动态规划
dog2503 小时前
圆锥曲线和二次曲线
开发语言·网络·人工智能·算法·php
Wadli3 小时前
27.单调队列
算法
Navigator_Z4 小时前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode