看一个节点有没有子节点,有子节点按左右顺序入队列,然后记录该节点的值
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> levelOrder (TreeNode root) {
// write code here
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new LinkedList();
q.offer(root);
if(root == null)
return res;
while(!q.isEmpty()){
ArrayList<Integer> arr = new ArrayList<>();
int count = q.size();
while(count-- > 0){
TreeNode tree = q.poll();
if(tree.left != null){
q.offer(tree.left);
}
if(tree.right != null){
q.offer(tree.right);
}
arr.add(tree.val);
}
res.add(arr);
}
return res;
}
}