题目:
代码(首刷自解 2024年1月24日):
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
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 == nullptr) return root;
queue<Node*> que;
Node* cur = root;
que.push(cur);
int size = 0;
while (!que.empty()) {
size = que.size();
while (size--) {
Node* node = que.front();
que.pop();
if (size == 0) node->next = nullptr;
else node->next = que.front();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return root;
}
};