来源
题目直达,力扣 = 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