classSolution{public:Node*connect(Node*root){Node*node=root;// The node just above current needlingwhile(node){Nodedummy(0);// Dummy node before needling// Needle children of nodefor(Node*needle=&dummy;node;node=node->next){if(node->left){// Needle left childneedle->next=node->left;needle=needle->next;}if(node->right){// Needle right childneedle->next=node->right;needle=needle->next;}}node=dummy.next;// Move node to the next level}returnroot;}};
classSolution{publicNodeconnect(Noderoot){Nodenode=root;// The node just above current needlingwhile(node!=null){Nodedummy=newNode();// Dummy node before needling// Needle children of nodefor(Nodeneedle=dummy;node!=null;node=node.next){if(node.left!=null){// Needle left childneedle.next=node.left;needle=needle.next;}if(node.right!=null){// Needle right childneedle.next=node.right;needle=needle.next;}}node=dummy.next;// Move node to the next level}returnroot;}}
classSolution:defconnect(self,root:'Node')->'Node':node=root# The node just above current needlingwhilenode:dummy=Node(0)# Dummy node before needling# Needle children of nodeneedle=dummywhilenode:ifnode.left:# Needle left childneedle.next=node.leftneedle=needle.nextifnode.right:# Needle right childneedle.next=node.rightneedle=needle.nextnode=node.nextnode=dummy.next# Move node to the next levelreturnroot