层序遍历处理over
queue队列的函数是 add/offer poll
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
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);
int time = 1;
while(!q.isEmpty()){
List<Integer> ans = new ArrayList<>();
int flag = 0;
for(int i=0; i<time; i++){
TreeNode node = q.poll();
ans.add(node.val);
if(node.left!=null){
q.offer(node.left);
flag++;
}
if(node.right!=null){
q.offer(node.right);
flag++;
}
}
res.add(ans);
time=flag;
}
return res;
}
}