示例:
二叉树:[3,9,20,null,null,15,7]
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
queue用到的方法
queue.offer()
queue.poll()
- Queue 中 add() 和 offer() 区别:
Queue 中 add() 和 offer()都是用来向队列添加一个元素。在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回 false 。 - poll()方法返回位于容器前面或队列开头的元素。当队列为空时,它返回null。
利用队列先进先出的特点,如例子中3入队列后,poll到数组[0]中,3的左右子树9,20入队列,依次循环,9poll,9的左右子树入队列,20poll,20的左右子树入队列,直到队列为空,返回数组。
arraylist和linkedlist区别:
主要区别:ArrayList是Array(动态数组)的数据结构,而LinkedList是Link(链表)的数据结构。
随机访问(get和set)时,ArrayList优于LinkedList;新增和删除操作,LinedList比较占优势。
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//定义一个返回数组
List<List<Integer>> res = new ArrayList<>();
if(root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()) {
//count代表一层有多少个节点
int count = queue.size();
//list记录每层的节点
List<Integer> list = new ArrayList();
//队列不为空,则poll根节点,add左右子树
for(int i=0; i<count; i++) {//循环遍历每一层的节点
TreeNode cur = queue.poll();
list.add(cur.val);//根节点出队列,进数组
if(cur.left != null) {
queue.offer(cur.left);
}
if(cur.right != null) {
queue.offer(cur.right);
}
}
res.add(list);
}
return res;
}
}