题目
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/cd73b37d9539acc6ad41843679efec5a.png)
方法一:直接让每层不是最后一个的节点指向此时队首元素
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/357cb7aff846e5d2dfae890a603fdd1f.png)
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Deque<Node> queue = new LinkedList<>();
Node node = root;
queue.offer(node);
List<Node> list = null;
while(!queue.isEmpty()){
int size = queue.size();
list = new ArrayList<>();
for(int i = 0 ; i < size ; i++){
node = queue.poll();
if(i == size - 1) node.next = null;
else node.next = queue.peek();
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
}
return root;
}
}
方法二:用list记录下每层的节点 然后再做链接
class Solution {
public Node connect(Node root) {
if(root == null) return null;
Deque<Node> queue = new LinkedList<>();
Node node = root;
queue.offer(node);
List<Node> list = null;
while(!queue.isEmpty()){
int size = queue.size();
list = new ArrayList<>();
for(int i = 0 ; i < size ; i++){
node = queue.poll();
list.add(node);
if(node.left != null) queue.offer(node.left);
if(node.right != null) queue.offer(node.right);
}
for(int i = 0 ; i < list.size() ; i++){
if(i == list.size()-1) list.get(i).next = null;
else list.get(i).next = list.get(i+1);
}
}
return root;
}
}