LeetCode 117. 填充每个节点的下一个右侧节点指针 II
思路:
用head与end去维护每一层的下一层,end维护next指针,head用来跳转到下一层。
代码:
/*
// 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 res = root;
while(root){
auto head =new Node(-1);
auto end = head;
for(auto p = root;p;p = p->next){
if(p->left) end = end->next=p->left;
if(p->right) end = end->next = p->right;
}
root = head->next;
}
return res;
}
};
评论区