剑指 Offer 32 - I. 从上到下打印二叉树
题目
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
前置知识:
标签:
思路
1.自己的思路(BFS)
代码
class Offer32IV0 {
public int[] levelOrder(TreeNode root) {
if (root == null){
return new int[0];
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()){
TreeNode poll = queue.poll();
list.add(poll.val);
if (poll.left != null){
queue.offer(poll.left);
}
if (poll.right != null){
queue.offer(poll.right);
}
}
return list.stream().mapToInt(Integer::intValue).toArray();
}
}
复杂度分析
- 时间复杂度:O(n), n为二叉树的数量
- 空间复杂度:O(n)
总结
树的最基本的广度优先遍历,需要注意的地方是实现队列时,添加元素和移除元素的方法的区别
- Queue 中 add() 和 offer()都是用来向队列添加一个元素。
在容量已满的情况下,add() 方法会抛出IllegalStateException异常,offer() 方法只会返回 false 。 - Queue 中 remove() 和 poll()都是用来从队列头部删除一个元素。
在队列元素为空的情况下,remove() 方法会抛出NoSuchElementException异常,poll() 方法只会返回 null 。