Offer.P32-I[从上到下打印二叉树] 方法一:层序遍历123456789101112131415161718192021222324252627/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */class Solution { public int[] levelOrder(TreeNode root) { List<Integer> list = new ArrayList<>(); Deque<TreeNode> queue = new ArrayDeque<>(); if (root != null) queue.addLast(root); while (!queue.isEmpty()) { TreeNode p = queue.pollFirst(); list.add(p.val); if (p.left != null) queue.addLast(p.left); if (p.right != null) queue.addLast(p.right); } int[] ans = new int[list.size()]; for (int i = 0; i < list.size(); i++) { ans[i] = list.get(i); } return ans; }} 时间复杂度:$O(n)$ 空间复杂度:$O(n)$