力扣 - 剑指 Offer 32 - I. 从上到下打印二叉树
题目
剑指 Offer 32 - I. 从上到下打印二叉树
思路1
- BFS广度优先搜索遍历二叉树,使用队列存储节点
- 算法执行流程如下:
- 如果
root
,不为空,先加入队列,否则直接结束(因为一个元素都没有了嘛) - 从队列
queue
中取出队头元素,存入列表res
中,然后如果他的左节 / 右节点点不为空,就加入到队列中 - 每次循环都从队头取出一个元素,然后判断是否存在左右子节点需要加入到队列中。。。直到队列为空,说明遍历结束
- 如果
代码
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) {
return new int[0];
}
Queue queue = new LinkedList();
List list = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
list.add(node.val);
// 判断左右子节点是否存在,存在的话加入到队列中
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
// 将list链表转换成int数组
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
复杂度分析
- 时间复杂度:\(O(N)\)
- 空间复杂度:\(O(N)\)