117.填充每个节点的下一个右侧节点指针 II (Medium)*
题目描述*
给定一个二叉树
struct Node {
int val;
Node *left;
Node *right;
Node *next;
}
填充它的每个 next 指针,让这个指针指向其下一个右侧节点。如果找不到下一个右侧节点,则将 next 指针设置为 NULL。
初始状态下,所有 next 指针都被设置为 NULL。
进阶*
你只能使用常量级额外空间。
使用递归解题也符合要求,本题中递归程序占用的栈空间不算做额外的空间复杂度。
代码*
不考虑空间的 bfs 完全适用,不用改。递归是 copy 的别人的,条件太多就很懵。。。换成迭代就很容易理解了。
class Solution {
public:
Node* connect(Node* root) {
queue<Node*> helpQueue;
if(root == nullptr) {
return nullptr;
}
Node *cur = root;
helpQueue.push(cur);
Node *pre = nullptr;
while(!helpQueue.empty()) {
int len = helpQueue.size();
pre = nullptr;
for(int i = 0; i < len; i++) {
cur = helpQueue.front();
helpQueue.pop();
if(i > 0) {
pre->next = cur;
}
pre = cur;
if(cur->left != nullptr) {
helpQueue.push(cur->left);
}
if(cur->right != nullptr) {
helpQueue.push(cur->right);
}
}
}
return root;
}
};
class Solution {
public:
Node* connect(Node* root) {
if(root == nullptr || root->left == nullptr && root->right == nullptr) {
return root;
}
if(root->left != nullptr && root->right != nullptr) {
root->left->next = root->right;
}
Node *cur = (root->right == nullptr) ? root->left : root->right;
Node *head = root->next;
while(head != nullptr && head->left == nullptr && head->right == nullptr) {
head = head->next;
}
cur->next = (head == nullptr) ? nullptr : ((head->left == nullptr) ? head->right : head->left);
connect(root->right);
connect(root->left);
return root;
}
};
class Solution {
public:
Node* connect(Node* root) {
Node *cur = root;
while(cur != nullptr) {
Node *dummy = new Node();
Node *tail = dummy;
while(cur != nullptr) {
if(cur->left != nullptr) {
tail->next = cur->left;
tail = tail->next;
}
if(cur->right != nullptr) {
tail->next = cur->right;
tail = tail->next;
}
cur = cur->next;
}
cur = dummy->next;
}
return root;
}
};
最后更新: July 23, 2022