AcWing 44. 分行从上往下打印二叉树
原题链接
中等
作者:
小轩喵灬
,
2025-01-13 11:37:47
,
所有人可见
,
阅读 1
/**
* 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) {
List<List<Integer>> res = new ArrayList<>();
Deque<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
int cnt = queue.size();
while(cnt-- > 0) {
TreeNode treeNode = queue.poll();
if (treeNode == null) {
continue;
}
list.add(treeNode.val);
queue.add(treeNode.left);
queue.add(treeNode.right);
}
if (list.size() != 0) {
res.add(list);
}
}
return res;
}
}