Skip to main content

116. Populating Next Right Pointers in Each Node

  • 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;

if (root->left)
{
root->left->next = root->right;
}

if (root->right)
{
root->right->next = root->next ? root->next->left : nullptr;
}

connect(root->left);
connect(root->right);
return root;
}
};
  • T: O(n)O(n)

  • S: O(n)O(n)

  • 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: O(n)O(n)
  • S: O(n)O(n)