LeetCode刷题进阶之从上到下打印二叉树(剑指Offer 32 - I)

一、题目
在这里插入图片描述
演示示例:
在这里插入图片描述
二、测试代码

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] levelOrder(TreeNode root) {
        List<Integer> list=new ArrayList<>();
        int[] res={};
        if(root==null){
            return res;
        }
        Queue<TreeNode> queue=new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            TreeNode temp=queue.poll();
            list.add(temp.val);
            if(temp.left!=null){
                queue.offer(temp.left);
            }
            if(temp.right!=null){
                queue.offer(temp.right);
            }
        }
        res=new int[list.size()];
        for(int i=0;i<list.size();i++){
            res[i]=list.get(i);
        }
    return res;
    }
}

三、运行情况
在这里插入图片描述

四、刷题总结

本题的主要思路步骤为:

(1)特例处理: 当树的根节点为空,则直接返回空列表 [] ;
(2)初始化: 打印结果列表 res = [] ,包含根节点的队列queue = [root] ;
(3)BFS 循环: 当队列 queue 为空时跳出;
(4)出队: 队首元素出队,记为 temp;
(5)打印: 将 temp.val 添加至列表 list 尾部;
(6)添加子节点: 若 temp的左(右)子节点不为空,则将左(右)子节点加入队列 queue ;
(7)返回值: 返回打印结果列表 res 即可。

传送门:二叉树的层次遍历

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值