leetcode第102题,二叉树的层级遍历(广度优先)
- 感觉自己的基础还是不够扎实,一直都不知道,LinkedList竟然实现了queue接口,对于普通的遍历方式,并不会要求list里面还是一个list的集合,就需要打入一个for循环.
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
LinkedList<List<Integer>> lists = new LinkedList<>();
if(root == null){
return lists;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
LinkedList<Integer> integers = new LinkedList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode poll = queue.poll();
integers.add(poll.val);
if (poll.left != null) {
queue.offer(poll.left);
}
if (poll.right != null) {
queue.offer(poll.right);
}
}
lists.add(integers);
}
return lists;
}
}
|