题目
解法
- 递归法:
左节点:
-
root有左节点和右节点,则左节点的next为右节点
-
root右节点为null,则查找父节点的兄弟节点的最左边子元素
右节点:
- root右节点不为null,其next为父节点的兄弟节点的最左边子元素
先构建右子树,再构建左子树,因为寻找父节点的兄弟节点是从左到右遍历的,如果右子树next没接上就遍历,会出错??
c++
class Solution {
public:
Node* connect(Node* root) {
if(root == NULL)
return root;
if(root->left)
{
if(root->right)
root->left->next = root->right;
else
root->left->next = findchild(root);
}
if(root->right)
root->right->next = findchild(root);
connect(root->right);
connect(root->left);
return root;
}
Node* findchild(Node* root)
{
if(root->next == NULL)
return NULL;
while(root->next)
{
if(root->next->left)
return root->next->left;
if(root->next->right)
return root->next->right;
root = root->next;
}
return NULL;
}
};
2.层次遍历法
初始化一个队列 q,将根结点放入队列中。当队列不为空的时候,记录当前队列大小为 n,从队列中以此取出 n个元素并通过这 n 个元素拓展新节点。如此循环,直到队列为空。
这样做可以保证每次遍历的 n 个点都是同一层的。我们可以在遍历每一层的时候修改这一层节点的 next 指针,这样就可以把每一层都组织成链表。
c语言
struct Node *connect(struct Node *root) {
if (!root) {
return NULL;
}
struct Node *q[10001];
int left = 0, right = 0;
q[right++] = root;
while (left < right) {
int n = right - left;
struct Node *last = NULL;
for (int i = 1; i <= n; ++i) {
struct Node *f = q[left++];
if (f->left) {
q[right++] = f->left;
}
if (f->right) {
q[right++] = f->right;
}
if (i != 1) {
last->next = f;
}
last = f;
}
}
return root;
}
c++
class Solution {
public:
Node* connect(Node* root) {
if (!root) {
return nullptr;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
Node *last = nullptr;
for (int i = 1; i <= n; ++i) {
Node *f = q.front();
q.pop();
if (f->left) {
q.push(f->left);
}
if (f->right) {
q.push(f->right);
}
if (i != 1) {
last->next = f;
}
last = f;
}
}
return root;
}
};