【刷爆力扣之二叉树】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;
}
相关推荐
Tiandaren4 小时前
Selenium 4 教程:自动化 WebDriver 管理与 Cookie 提取 || 用于解决chromedriver版本不匹配问题
selenium·测试工具·算法·自动化
岁忧5 小时前
(LeetCode 面试经典 150 题 ) 11. 盛最多水的容器 (贪心+双指针)
java·c++·算法·leetcode·面试·go
chao_7895 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说7 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
Maybyy7 小时前
力扣61.旋转链表
算法·leetcode·链表
卡卡卡卡罗特9 小时前
每日mysql
数据结构·算法
chao_78910 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找
lifallen10 小时前
Paimon 原子提交实现
java·大数据·数据结构·数据库·后端·算法
lixzest10 小时前
C++ Lambda 表达式详解
服务器·开发语言·c++·算法
EndingCoder11 小时前
搜索算法在前端的实践
前端·算法·性能优化·状态模式·搜索算法