117. Populating Next Right Pointers in Each Node II
题目大意
Populate each next
pointer to point to its next right node. If there is no next right node, the next
pointer should be set to NULL.
Initially, all next
pointers are set to NULL.
中文释义
填充每个节点的 next
指针,使其指向其右侧的下一个节点。如果没有右侧的下一个节点,则将 next
指针设置为 NULL。
初始时,所有 next
指针都设置为 NULL。
示例
示例 1:
输入: root
= [1,2,3,4,5,null,7]
输出: [1,#,2,3,#,4,5,7,#]
示例 2:
输入: root = []
输出: []
限制条件
- The number of nodes in the tree is in the range
[0, 6000]
. -100 <= Node.val <= 100
解题思路
方法
该方法使用层次遍历(广度优先搜索)来连接每个节点的 next
指针。
-
检查空树:
- 如果根节点为空,直接返回
nullptr
。
- 如果根节点为空,直接返回
-
使用队列进行层次遍历:
- 使用一个队列
node_queue
存储每层的节点。
- 使用一个队列
-
遍历每一层:
- 对于每一层的节点,依次从队列中取出并连接
next
指针。 - 如果节点是这一层的最后一个节点,将其
next
指向nullptr
;否则,将其next
指向队列的下一个节点。
- 对于每一层的节点,依次从队列中取出并连接
-
添加子节点到队列:
- 将当前节点的左右子节点添加到队列中,以便下一轮遍历。
-
更新队列大小:
- 更新队列的大小,准备遍历下一层的节点。
-
返回根节点:
- 在遍历完所有层次后,返回根节点。
代码
class Solution {
public:
Node* connect(Node* root) {
if (root == nullptr) return root;
queue<Node*> node_queue;
node_queue.push(root);
int count = 1;
while (!node_queue.empty()) {
int temp_count = 0;
for (int i = 0; i < count; i++) {
Node* node = node_queue.front();
node_queue.pop();
if (i == count - 1) {
node -> next = nullptr;
} else {
node -> next = node_queue.front();
}
if (node -> left) {
node_queue.push(node -> left);
temp_count++;
}
if (node -> right) {
node_queue.push(node -> right);
temp_count++;
}
}
count = temp_count;
}
return root;
}
};