解题思路
先给下一层建立一个dummyHead 之后把这一层的孩子顺次接上 搞定 去往下一层
代码
class Solution {
public Node connect(Node root) {
if(root == null) return root;
Node start = root;
//遍历所有层
while(start != null){
Node nextLayerDummyHead = new Node(0);//dummyHead 能节约后面很多判断
Node cur = start;
Node nextLayerCur = nextLayerDummyHead;
//遍历每层所有节点
while(cur != null){
if(cur.left != null){//如果有左孩子 接上
nextLayerCur.next = cur.left;
nextLayerCur = cur.left;
}
if(cur.right != null){//如果有右孩子 接上
nextLayerCur.next = cur.right;
nextLayerCur = cur.right;
}
cur = cur.next;
}
start = nextLayerDummyHead.next;
}
return root;
}
}