AcWing 45. 之字形打印二叉树
原题链接
中等
作者:
STU756
,
2020-09-01 13:13:47
,
所有人可见
,
阅读 349
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root == null) return ans;
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
boolean flag = true;
while(!queue.isEmpty()){
int size = queue.size();
List<Integer> list = new ArrayList<>();
while(size-- > 0) {
TreeNode node = queue.pollLast();
list.add(node.val);
if(node.left!=null) queue.addFirst(node.left);
if(node.right!=null) queue.addFirst(node.right);
}
flag = !flag;
if(flag) Collections.reverse(list);
ans.add(list);
}
return ans;
}