一枪秒了,有什么好说的。这种要按照层完成操作的,一般都需要用到广度优先遍历。
class Solution {
public int[] levelOrder(TreeNode root) {
if(root == null)
return new int[0];
Queue<TreeNode> print = new LinkedList();
ArrayList<Integer> res = new ArrayList();
print.add(root);
while(!print.isEmpty()){
TreeNode head = print.poll();
res.add(head.val);
if(head.left != null)
print.add(head.left);
if(head.right != null)
print.add(head.right);
}
int[] ans = new int[res.size()];
for(int i = 0; i < ans.length; i++)
ans[i] = res.get(i);
return ans;
}
}