一、需求
- 从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
二、层序遍历法
2.1 思路分析
- 题目要求的二叉树从上到下打印(即按层打印),又称为二叉树的广度优先搜索(BFS)。
- BFS通常借助队列的先入先出特性来实现。
2.2 算法流程
- 特例处理:当树的根结点为空,则直接返回空列表[ ];
- 初始化:打印结果列表res = [ ],包含根结点的队列queue = [root];
- BFS循环:当队列queue为空时跳出:
1.出队:队首元素出队,记为node;
2.打印:将node.val添加至列表tmp尾部;
3.添加子结点:若node的左(右)子结点不为空,则将左(右)子结点加入到队列;
4.返回值:返回打印结果列表res即可。
2.3 代码实现
class Solution {
public int[] levelOrder(TreeNode root) {
if(root == null) return new int[0];
Queue<TreeNode> queue = new LinkedList<>(){{ add(root); }};
ArrayList<Integer> ans = new ArrayList<>();
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
ans.add(node.val);
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
int[] res = new int[ans.size()];
for(int i = 0; i < ans.size(); i++) {
res[i] = ans.get(i);
}
return res;
}
}
2.4 复杂度分析
- 时间复杂度为O(N),N是二叉树的结点个数。
- 空间复杂度为O(N)。
三、参考地址
作者:Krahets