广度优先搜索
class Solution {
public Node connect(Node root) {
Queue<Node> queue = new LinkedList<>();
if (root == null){
return root;
}
queue.add(root);
while (!queue.isEmpty()){
int size = queue.size();
for (int i = 0; i < size; i++) {
Node temp = queue.poll();
/**
* 每一层最后一个节点的next指向null,其他节点指向下一个出队的节点
*/
if (i == size - 1){
temp.next = null;
}
else {
temp.next = queue.peek();
}
if (temp.left != null){
queue.add(temp.left);
}
if (temp.right != null){
queue.add(temp.right);
}
}
}
return root;
}
}
/**
* 时间复杂度 O(n)
* 空间复杂度 O(n)
*/
https://leetcode-cn.com/problems/populating-next-right-pointers-in-each-node/