解法:
class Solution {
public int[] levelOrder(TreeNode root) {
if(root==null){
return new int[]{};
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Integer> result = new ArrayList<>();
while(!queue.isEmpty()){
TreeNode node = queue.poll();
result.add(node.val);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
// 根据题目要求,把 list 转化为数组
int[] res = new int[result.size()];
for (int i = 0; i < result.size(); i++) {
res[i] = result.get(i);
}
return res;
}
}
注意:
- 该题要求返回的是数组
- 列表需要转换为数组
- 二叉树的层级遍历需要队列
参考:
- https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/solution/mian-shi-ti-32-i-cong-shang-dao-xia-da-yin-er-ch-4/
- https://blog.algomooc.com/032.html#%E4%BA%8C%E3%80%81%E5%8F%82%E8%80%83%E4%BB%A3%E7%A0%81