题目描述
思路分析
二叉树+BFS思想
和这道题差别不大,差别就是维护一个
h
e
a
d
−
t
a
i
l
head-tail
head−tail链表,把当前层串起来
代码实现
/*
// 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 root;
auto cur=root;
while(cur){
auto head=new Node(-1);
auto tail=head;
for(auto p=cur;p;p=p->next){
if(p->left) tail=tail->next=p->left;
if(p->right) tail=tail->next=p->right;
}
cur=head->next;
}
return root;
}
};