题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。

来源:https://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288?tpId=13&tqId=11213&tPage=3&rp=3&ru=%2Fta%2Fcoding-interviews&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking

1.非递归:利用队列

import java.util.ArrayList;
import java.util.LinkedList;

/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;

}

}
*/
public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
if(pRoot==null){
return new ArrayList<ArrayList<Integer>>();
}
LinkedList<TreeNode> queue = new LinkedList<>();
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
queue.offer(pRoot);
while(!queue.isEmpty()){
int size = queue.size();
ArrayList<Integer> list = new ArrayList<>(size);
for(int i = 0;i<size;i++){
TreeNode node = queue.poll();
list.add(node.val);
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
res.add(list);
}
return res;
}

}