利用BFS遍历整棵树,利用队列的size()方法,将节点分组,一一设置下一节点
class Solution {
public Node connect(Node root) {
if(root==null){
return root;
}
Deque<Node> queue=new LinkedList<>();
queue.offer(root);
Node tmp=new Node();
Node pre=new Node();
while(!queue.isEmpty()){
int n=queue.size();
pre=queue.poll();
if(pre.left!=null){
queue.offer(pre.left);
queue.offer(pre.right);
}
for(int i=1;i<n;i++){
tmp=queue.poll();
if(tmp.left!=null){
queue.offer(tmp.left);
queue.offer(tmp.right);
}
pre.next=tmp;
pre=tmp;
}
}
return root;
}
}
省空间升级版
class Solution {
public Node connect(Node root) {
if(root==null){
return root;
}
Deque<Node> queue=new LinkedList<>();
queue.offer(root);
Node tmp=new Node();
while(!queue.isEmpty()){
int n=queue.size();
for(int i=0;i<n;i++){
tmp=queue.poll();
if(i<n-1){
tmp.next=queue.peek();
}
if(tmp.left!=null){
queue.offer(tmp.left);
}
if(tmp.right!=null){
queue.offer(tmp.right);
}
}
}
return root;
}
}
在进行时间复杂度分析时,由于需要不断进行入队和出队操作,使得整个算法的时间效率不是很高,可以省去队列,而是采用指针记录的方法,提高运算效率,代码如下:
class Solution {
public Node connect(Node root) {
if(root==null){
return root;
}
Node cur=root;
while(cur!=null){
Node dummy=new Node();
Node pre=dummy;
while(cur!=null){
if(cur.left!=null){
pre.next=cur.left;
pre=pre.next;
}
if(cur.right!=null){
pre.next=cur.right;
pre=pre.next;
}
cur=cur.next;
}
cur=dummy.next;
}
return root;
}
}