LeetCode刷题038 从上到下打印二叉树 II

该代码实现了一个Java方法,用于从上到下按层打印二叉树,每层节点按从左到右的顺序排列。方法使用了队列进行广度优先搜索(BFS),维护当前层和下一层的节点数,将每层的节点值添加到列表中并返回结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

剑指 Offer 32 - II. 从上到下打印二叉树 II

题目

从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7
返回其层次遍历结果:

[
  [3],
  [9,20],
  [15,7]
]
提示:
节点总数 <= 1000
题解

层次遍历,用变量存储下一层的节点数量即可

Code
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        if(root == null)
            return new ArrayList<List<Integer>>();
        ArrayList<List<Integer>> lists = new ArrayList<>();
        ArrayDeque<TreeNode> q = new ArrayDeque<>();
        q.add(root);
        int thisCount = 1;
        int nextCount = 0;
        ArrayList<Integer> list = new ArrayList<>();
        while(!q.isEmpty()){
            if(thisCount > 0){
                TreeNode t = q.poll();
                list.add(t.val);
                thisCount --;
                if(t.left != null){
                    q.add(t.left);
                    nextCount ++;
                }
                if(t.right != null){
                    q.add(t.right);
                    nextCount ++;
                }
            }else{
                lists.add(list);
                thisCount = nextCount;
                nextCount = 0;
                list = new ArrayList<>();
            }
        }
        lists.add(list);
        return lists;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值