剑指 Offer 32 - I. 从上到下打印二叉树
层序遍历
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) return new int[0];
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
for (int i = queue.size(); i > 0; i--) {
TreeNode cur = queue.poll();
list.add(cur.val);
if (cur.left != null) queue.add(cur.left);
if (cur.right != null) queue.add(cur.right);
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}