文章目录
原题题目
代码实现(首刷看了一下思路 恍然大悟 没想到模拟层序遍历 一直在想递归怎么能够实现 记录左右节点)
class Solution {
public:
Node* connect(Node* root) {
if(!root) return root;
auto nowptr = root;
while(nowptr)
{
Node* first = nullptr,*preptr = nullptr;
while(nowptr)
{
if(nowptr->left)
{
if(!first) first = nowptr->left;
else preptr->next = nowptr->left;
preptr = nowptr->left;
}
if(nowptr->right)
{
if(!first) first = nowptr->right;
else preptr->next = nowptr->right;
preptr = nowptr->right;
}
nowptr = nowptr->next;
}
nowptr = first;
}
return root;
}
};