不分行从上往下打印二叉树
从上往下打印出二叉树的每个结点,同一层的结点按照从左到右的顺序打印。
样例
输入如下图所示二叉树[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<Integer> printFromTopToBottom(TreeNode root) {
List<Integer> list = new ArrayList<>();
Queue<TreeNode> q = new LinkedList<>();
if(root == null){
return list;
}
q.offer(root);
while(q.size() != 0){
TreeNode tmp = q.peek();
q.poll();
list.add(tmp.val);
if(tmp.left != null)
q.offer(tmp.left);
if(tmp.right != null)
q.offer(tmp.right);
}
return list;
}
}