Create 117.cpp

This commit is contained in:
Kirigaya Kazuto 2023-11-03 02:13:30 +08:00 committed by GitHub
parent 1be36799dd
commit 8fbe78e621
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

51
LeetCode/117.cpp Normal file
View File

@ -0,0 +1,51 @@
class Solution {
public:
Node* processLevel(Node* leftMost) {
Node* nextLevelLeftMost = nullptr;
Node* nextLevelNext = nullptr;
for (Node* current = leftMost; current != nullptr; current = current->next) {
if (current->left && current->right) {
current->left->next = current->right;
if (!nextLevelLeftMost) {
nextLevelLeftMost = current->left;
nextLevelNext = current->right;
}
else {
nextLevelNext->next = current->left;
nextLevelNext = current->right;
}
}
else if (current->left) {
if (!nextLevelLeftMost) {
nextLevelLeftMost = current->left;
nextLevelNext = current->left;
}
else {
nextLevelNext->next = current->left;
nextLevelNext = current->left;
}
}
else if (current->right) {
if (!nextLevelLeftMost) {
nextLevelLeftMost = current->right;
nextLevelNext = current->right;
}
else {
nextLevelNext->next = current->right;
nextLevelNext = current->right;
}
}
}
return nextLevelLeftMost;
}
Node* connect(Node* root) {
Node* nextLevelEntry = root;
while (nextLevelEntry) {
nextLevelEntry = processLevel(nextLevelEntry);
}
return root;
}
};