思路:
// @Title: 填充每个节点的下一个右侧节点指针 II (Populating Next Right Pointers in Each Node II)
// @Author: qisiii
// @Date: 2024-09-14 23:51:28
// @Runtime: 1 ms
// @Memory: 43.2 MB
// @comment:
// @flag:
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if (root == null) {
return root;
}
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
Node right=null;
while (size > 0) {
Node node = queue.poll();
node.next=right;
right=node;
if (node.right != null) {
queue.offer(node.right);
}
if (node.left != null) {
queue.offer(node.left);
}
size--;
}
}
return root;
}
}