题目链接
法一
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root == null){
return ans;
}
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()){
List<Integer> row = new ArrayList<>();
int size = q.size();
while(size > 0){
TreeNode now = q.peek();
q.poll();
row.add(now.val);
if(now.left != null){
q.offer(now.left);
}
if(now.right != null){
q.offer(now.right);
}
size--;
}
ans.add(row);
}
return ans;
}
本地测试
lay.showTitle(102);
Solution102 sol102 = new Solution102();
List<Integer> arr102 = Arrays.asList(3,9,20,null,null,15,7);
TreeNode root102 = treeOpt.createTreeByLayerOrder(arr102);
treeOpt.layerOrder(root102);
List<List<Integer>> ans102 = sol102.levelOrder(root102);
arrayOpt.showIntLists(ans102);