分行从上往下打印二叉树
从上到下按层打印二叉树,同一层的结点按从左到右的顺序打印,每一层打印到一行。
样例
输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
8
/ \
12 2
/
6
/
4
输出:[[8], [12, 2], [6], [4]]
BFS
时间复杂度O(n)
class Solution {
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
List<Integer> list1 = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root==null){
return list;
}
q.offer(root);
q.offer(null);
while(q.size()!=0){
if(q.peek() == null){
if(list1.size() == 0){
break;
}
q.poll();
list.add(list1);
list1 = new ArrayList();
q.offer(null);
continue;
}
TreeNode tmp = q.peek();
q.poll();
list1.add(tmp.val);
if(tmp.left!=null){
q.offer(tmp.left);
}
if(tmp.right!=null){
q.offer(tmp.right);
}
}
return list;
}
}