leetcode 116. 填充每个节点的下一个右侧节点指针
队列(BFS):
/*
// 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 NULL;
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* current=NULL;
Node* prev=NULL;
int len=q.size();
for(int i=0;i<len;i++)
{
current=q.front();
if(prev)prev->next=current;
q.pop();
if(current->left)q.push(current->left);
if(current->right)q.push(current->right);
prev=current;
}
}
return root;
}
};
拉链法(递归)
class Solution {
public:
void func(Node* A,Node* B)
{
// A->next is B.
if(!A)return;
func(A->left,A->right);
A->next=B;
func(A->right,B?B->left:NULL);
}
Node* connect(Node* root) {
// 拉链法
func(root,NULL);
return root;
}
};
拉链法(非递归)
class Solution {
public:
Node* connect(Node* root) {
// 拉链法
// func(root,NULL);
// 将递归修改为while
if (!root) return NULL;
Node* now = new Node;
Node* leftmost = new Node;
now = root;
leftmost = root;
while (now->left) {
now->left->next = now->right; // 当前节点的左节点的next指向右节点
if (now->next) { //将当前节点的右节点的next指向 下一节点的左节点
now->right->next = now->next->left;
now = now->next; // 更新当前节点
}
else {
now = leftmost->left; // 若当前节点没有next,更新当前节点为当前层的最左节点的左节点。
leftmost = now;
}
}
return root;
}
};