「这是我参与2022首次更文挑战的第29天,活动详情查看:2022首次更文挑战」。
题目描述
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
提示:
- 树中节点数目在范围 [0, 2000] 内
- -1000 <= Node.val <= 1000
题目链接:二叉树的层序遍历
思路介绍
在队列中添加根节点和一个标记第一层结束的哨兵节点,在队列不为空时进行循环,遇到节点,将节点值加入当前层列表,将子节点加入队列;遇到哨兵,表示当前层已经结束,将当前层列表加入结果列表;如果该哨兵之后还有元素,则在队列末尾加入新的哨兵。将当前层移入结果队列,并新建下一层列表;如果该哨兵之后没有元素,表示遍历结束
采用null来间隔需要进行初始化: 首先将root offer进queue中,再将null插到队列尾部,表示层级的结束; 进行while判断(当队列的首个元素为null则需要进行判断,如果队列长度不为1证明还有元素仍需要进行循环,若长度为1则代表队列结束)若队列首个元素为null,则代表上一层级为0,需要把上一层级的list(tempResult)加入result;将tempResult进行初始化;将队列元素进行poll弹出,重新offer如一个null,在null之前则是一个层级!!! 这一步非常关键,能够区分一个个层级 若不为null,则从队列中将元素弹出,并把该结点左右不为null的结点offer进队列中;当跳出while循环的时候,需要把tempresult添加进result中!
代码
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root==null){
return result;
}
Queue<TreeNode> tempQueue = new LinkedList<>();
tempQueue.offer(root);
tempQueue.offer(null);
List<Integer> tempResult = new ArrayList<>();
while ((tempQueue.peek() == null && tempQueue.size() !=1) || tempQueue.peek()!=null){
if (tempQueue.peek()==null){
result.add(tempResult);
tempResult = new ArrayList<>();
tempQueue.poll();
tempQueue.offer(null);
continue;
}
root = tempQueue.peek();
tempResult.add(root.val);
tempQueue.poll();
if (root.left!=null){
tempQueue.offer(root.left);
}
if (root.right!=null){
tempQueue.offer(root.right);
}
}
result.add(tempResult);
return result;
}
}
运行结果
执行结果:通过
执行用时:1 ms,
内存消耗:41.5MB