题目:biubiu
题意:给二叉树多添加了一个next属性,让next指向他右边的节点。
例如:
思路一:递归记录每一层这个时候的左边的节点。
/*
// 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:
void dfs(Node* root,int x){
if(!root){
return ;
}
root->next=NULL;
if(p.size()==x){
p.push_back(root);
}else{
p[x]->next=root;
p[x]=root;
}
dfs(root->left,x+1);
dfs(root->right,x+1);
return ;
}
Node* connect(Node* root) {
if(!root)
return root;
dfs(root,0);
return root;
}
private:
vector<Node*>p;
};
思路二:
层次遍历,通过队列将没一层压入。
class Solution {
public:
Node* connect(Node* root) {
if(!root){
return root;
}
queue<Node*>p;
p.push(root);
p.push(NULL);
Node* rootl,*rootr;
while(!p.empty()){
rootl=p.front();
p.pop();
while(rootl){
if(rootl&&rootl->left)
p.push(rootl->left);
if(rootl&&rootl->right)
p.push(rootl->right);
if(p.empty())
break;
rootr=p.front();
p.pop();
rootl->next=rootr;
rootl=rootr;
}
if(p.empty())
break;
rootl=NULL;
p.push(rootl);
}
return root;
}
};
思路三:通过next来进行逐层遍历。next使每层变成了一个单链表,通过遍历这层单链表来对下层进行next的更新。
class Solution {
public:
void change(Node* &l,Node* &p,Node* &r){
if(p==nullptr){
return ;
}
if(!l){
l=p;
}
if(r){
r->next=p;
}
r=p;
return ;
}
Node* connect(Node* root) {
if(!root){
return root;
}
Node* start=root;
while(start){
Node* l,*r;
l=nullptr;
r=nullptr;
for(Node* p = start ; p !=nullptr; p = p->next){
change(l,p->left,r);
change(l,p->right,r);
}
start=l;
}
return root;
}
};