【刷爆力扣之二叉树】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;
}
相关推荐
CS创新实验室8 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
海石10 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石10 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx10 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
imbackneverdie11 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃12 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录13 小时前
prompt-optimizer skill
算法
万法若空14 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表
退休倒计时14 小时前
【每日一题】LeetCode 437. 路径总和 III TypeScript
算法·leetcode·typescript
学逆向的14 小时前
汇编——内存
开发语言·汇编·算法·网络安全