117. Populating Next Right Pointers in Each Node II
- Recursion
/*
// 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) return nullptr;
// 使用一個指標指向下一個節點
Node* cur = root->next;
while (cur)
{
if (cur->left)
{
cur = cur->left;
break;
}
if (cur->right)
{
cur = cur->right;
break;
}
cur = cur->next;
}
if (root->right)
{
root->right->next = cur;
}
if (root->left)
{
root->left->next = root->right ? root->right : cur;
}
connect(root->right);
connect(root->left);
return root;
}
};
-
T:
-
S:
-
Iteration
/*
// 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) return nullptr;
queue<Node*> q{{root}};
while (!q.empty())
{
int qSize = q.size();
for (int i = 0; i < qSize; i++)
{
Node* node = q.front(); q.pop();
if (i < qSize - 1)
{
// 如果不是最末端的 node,node->next 指到下一個節點
node->next = q.front();
}
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return root;
}
};
-
T:
-
S:
-
Space O(1)
/*
// 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) {
Node* dummy = new Node(-1);
Node* cur = dummy;
Node* head = root;
while (root)
{
if (root->left)
{
cur->next = root->left;
cur = cur->next;
}
if (root->right)
{
cur->next = root->right;
cur = cur->next;
}
root = root->next;
if (!root)
{
cur = dummy;
root = dummy->next;
dummy->next = NULL;
}
}
return head;
}
};
- T:
- S: