public Node connect(Node root) {
if(root == null) return root;
Deque<Node> q = new LinkedList();
q.offer(root);
while(!q.isEmpty()) {
int size = q.size();
for(int i = 0; i < size; i++) {
Node node1 = q.poll();
if(node1.left != null) q.offer(node1.left);
if(node1.right != null) q.offer(node1.right);
if(i != size -1) {
Node node2 = q.peek();
node1.next =node2;
}
else {
node1.next = null;
}
}
}
return root;
}