从上到下按层打印二叉树,同一层的节点按从左到右的顺序打印,每一层打印到一行。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
提示:
- 节点总数 <= 1000
分析:
方法:队列+BFS
这道题和 I. 从上到下打印二叉树 解题思路一样,不同点在于要分层把该层所有节点添加到 List集合 中,因此我们可以在遍历该层的时候,记录队列此时的长度,然后根据该长度添加指定节点的值到 List集合 中,然后再将该层集合添加到结果集合中。
时间复杂度:O(n)
空间复杂度:O(n)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//判断空树
if(root == null){
return new ArrayList();
}
//定义队列
Deque<TreeNode> queue = new ArrayDeque<>();
//入栈
queue.offerLast(root);
//创建List集合存储每层的List集合
List<List<Integer>> res = new ArrayList<>();
//遍历
while(!queue.isEmpty()){
//获取队列长度
int size = queue.size();
//定义List集合存储该层的节点值
List<Integer> list = new ArrayList<>();
//按层次遍历
while(size-- > 0){
//出栈
TreeNode node = queue.pollFirst();
//添加节点值
list.add(node.val);
//左节点不为空添加左节点
if(node.left != null){
queue.offerLast(node.left);
}
//右节点不为空添加右节点
if(node.right != null){
queue.offerLast(node.right);
}
}
//将List集合添加到List集合中
res.add(list);
}
return res;
}
}
题目来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-ii-lcof