AcWing 45. 之字形打印二叉树-java
原题链接
中等
作者:
单箭头
,
2019-05-12 22:15:33
,
所有人可见
,
阅读 1254
java 代码
class Solution {
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> res=new ArrayList<>();
if(root==null) return res;
Queue<TreeNode> stack=new LinkedList<>();
stack.offer(root);
boolean T= true;
int cnt=1,tmp=0;
List<Integer> list=new ArrayList<>();
while(!stack.isEmpty()){
TreeNode cur=stack.poll();
if(T) list.add(cur.val);
else list.add(0,cur.val);
cnt--;
if(cur.left!=null) {
stack.offer(cur.left);
tmp++;
}
if(cur.right!=null) {
stack.offer(cur.right);
tmp++;
}
if(cnt==0){
cnt=tmp;
tmp=0;
res.add(list);
list=new ArrayList<>();
T=!T;
}
}
return res;
}
}