leetcode-102 二叉树的层序遍历
嗯,简单的bfs,由于每层需要构成一个数组,因此在遍历的时候,每层节点一起处理。
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) return res;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root); // add() 方法失败的时候抛出异常
while(! q.isEmpty()){
int size = q.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++){
TreeNode node = q.poll();
list.add(node.val);
if (node.left != null){
q.offer(node.left);
}
if (node.right != null){
q.offer(node.right);
}
}
res.add(list);
}
return res;
}
}