【题目描述】
Acwing 44. 分行从上往下打印二叉树
【思路】
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
Queue<TreeNode> q = new LinkedList<>();
List<List<Integer>> res = new ArrayList<>();
if( root == null ) return res;
q.offer(root);
while( !q.isEmpty() ){
int size = q.size();//该层节点数
List<Integer> sub = new ArrayList<>();
while( size -- > 0){
//弹出节点
TreeNode node = q.poll();
if( node.left != null) q.offer(node.left);
if( node.right != null) q.offer(node.right);
sub.add(node.val);
}
res.add(sub);
}
return res;
}
}