AcWing 44. 分行从上往下打印二叉树--java
原题链接
中等
作者:
嘻嘻嘻o
,
2020-02-23 19:16:28
,
所有人可见
,
阅读 524
java 代码
/**
* 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>> ans=new ArrayList<>();
if(root==null)return ans;
Queue<TreeNode> q=new LinkedList<>();
List<Integer>level=new ArrayList<>();
q.add(root);
q.add(null);
while (!q.isEmpty()){
TreeNode tmp=q.poll();
if(tmp==null){
ans.add(new LinkedList<>(level));
level.clear();
if(q.isEmpty())break;
else
{
q.add(null);
continue;
}
}
level.add(tmp.val);
if(tmp.left!=null)q.add(tmp.left);
if(tmp.right!=null)q.add(tmp.right);
}
return ans;
}
}