queue的各种方法, 由剑指 Offer 32 - I. 从上到下打印二叉树(广度优先搜索,BFS)引出

来源

题目直达,力扣 = https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/

从 剑指 Offer 32 - I. 从上到下打印二叉树 题 思考 queue 中的方法记录
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

题目描述:

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

3
/ \
9 20
/ \ / \
null null 15 7

返回:
[3,9,20,15,7]

题解:

/**
 * 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) {
        if(root == null){
            return new int[]{};
        }
        // 初始化一个以根节点开头的队列
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        // 初始化一个目标集合, 最后将目标集合转为数组即可, 不能直接使用数组,因为不知道数组大小
        List<Integer> target = new ArrayList<>();
        // 队列为空时停止
        while(!queue.isEmpty()){
            // poll函数 将元素从队列中取出, 先进先出
            TreeNode node = queue.poll();
            // 获取当前节点的值, 分为 val, 和 next
            target.add(node.val);
            // 按照题目要求, 同层级按照 从左到右打印, 那么久按照先存 左再存 右, 先进先出的方式存储
            if(node.left != null){
                queue.add(node.left);
            }
            if(node.right != null){
                queue.add(node.right);
            }
        }
        // 待返回的数据大小
        int size = target.size();
        int[] reslut = new int[size];
        for(int i=0; i < size; i++){
            reslut[i] = target.get(i);
        }
        return reslut;
    }
}

队列 queue 的使用

队列 数据结构

先进先出 (FIFO)

实现方式

经常为 LinkedList
Queue<String> queue = new LinkedList<>();
或者 LinkedBlockingQueue
Queue<String> queue1 = new LinkedBlockingQueue<>();

public LinkedBlockingQueue(int capacity) {
        if (capacity <= 0) throw new IllegalArgumentException();
        this.capacity = capacity;
        last = head = new Node<E>(null);
    }

常用方法

添加元素
  • add(E e); 往队列中添加元素, 当队列满时, 报异常 java.lang.IllegalStateException: Queue full
  • offer(E e); 往队列中添加元素, 当队列满时, 返回 false
  • 正常情况下, 添加成功均返回 true
移除队首元素
  • E remove(); 从对首移除元素, 如果队列为空, 也就是队首 无数据时, 报异常 NoSuchElementException
  • E poll(); 从对首移除元素, 如果队列为空, 也就是队首 无数据时, 返回 null
获取队首元素, 但不移除
  • E element(); 从对首移除元素, 如果队列为空, 也就是队首 无数据时, 报异常 NoSuchElementException
  • E peek(); 从对首移除元素, 如果队列为空, 也就是队首 无数据时, 返回 null

其实这都是 在 Queue 这接口里面可以看见的, 所以这就是所谓的多看源码吧

参考文档 = https://blog.csdn.net/qq_41026809/article/details/90647569

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值