Given a binary tree, connect each node to its immediate right neighbor at the same level using the nextRight pointer. If no such neighbor exists, set the nextRight pointer to NULL.
[Naive Approach] Level Order Traversal - O(n) Time and O(n) Space
The idea is to traverse the binary tree level by level using a queue and connect adjacent nodes using their nextRight pointers.
Insert the root node into the queue.
Store the queue size in nodeCount to identify the number of nodes at the current level.
Process exactly nodeCount nodes, removing each node from the queue.
Set each node's nextRight to the next node at the same level using q.front(). If it is the last node at that level, set nextRight to NULL.
Add the left and right children of each node to the queue, if they exist.
Repeat until the queue becomes empty.
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left;Node*right;Node*nextRight;Node(intkey){data=key;left=nullptr;right=nullptr;nextRight=nullptr;}};// Connect nodes using node count (level size)Node*connect(Node*root){if(!root)returnroot;queue<Node*>q;q.push(root);while(!q.empty()){intnodeCount=q.size();for(inti=0;i<nodeCount;i++){Node*node=q.front();q.pop();// Set nextRightif(i==nodeCount-1)node->nextRight=nullptr;elsenode->nextRight=q.front();// Push childrenif(node->left)q.push(node->left);if(node->right)q.push(node->right);}}returnroot;}// Print level order using nextRight pointersvoidprintLevels(Node*root){Node*levelStart=root;while(levelStart!=nullptr){Node*curr=levelStart;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->nextRight;}cout<<"# ";// Find the first node of the next levelif(levelStart->left!=nullptr)levelStart=levelStart->left;elseif(levelStart->right!=nullptr)levelStart=levelStart->right;elsebreak;}}intmain(){// Constructed binary tree// 10// / \ // 8 2// / / // 3 4 Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->right->left=newNode(4);connect(root);printLevels(root);return0;}
Java
importjava.util.LinkedList;importjava.util.Queue;classNode{intdata;Nodeleft,right,nextRight;Node(intkey){data=key;left=right=nextRight=null;}}classGFG{// Connect nodes using node count (level size)staticNodeconnect(Noderoot){if(root==null)returnroot;Queue<Node>q=newLinkedList<>();q.add(root);while(!q.isEmpty()){intnodeCount=q.size();for(inti=0;i<nodeCount;i++){Nodenode=q.poll();// Set nextRightif(i==nodeCount-1)node.nextRight=null;elsenode.nextRight=q.peek();// Push childrenif(node.left!=null)q.add(node.left);if(node.right!=null)q.add(node.right);}}returnroot;}// Print level order using nextRight pointersstaticvoidprintLevels(Noderoot){NodelevelStart=root;while(levelStart!=null){Nodecurr=levelStart;while(curr!=null){System.out.print(curr.data+" ");curr=curr.nextRight;}System.out.print("# ");// Find the first node of the next levelif(levelStart.left!=null)levelStart=levelStart.left;elseif(levelStart.right!=null)levelStart=levelStart.right;elsebreak;}}publicstaticvoidmain(String[]args){// Constructed binary tree// 10// / \// 8 2// / /// 3 4Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root);}}
Python
fromcollectionsimportdequeclassNode:def__init__(self,key):self.data=keyself.left=Noneself.right=Noneself.nextRight=None# Connect nodes using node count (level size)defconnect(root):ifnotroot:returnrootq=deque([root])whileq:nodeCount=len(q)foriinrange(nodeCount):node=q.popleft()# Set nextRightifi==nodeCount-1:node.nextRight=Noneelse:node.nextRight=q[0]# Push childrenifnode.left:q.append(node.left)ifnode.right:q.append(node.right)returnroot# Print level order using nextRight pointersdefprintLevels(root):levelStart=rootwhilelevelStartisnotNone:curr=levelStartwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextRightprint("#",end=" ")# Find the first node of the next leveliflevelStart.leftisnotNone:levelStart=levelStart.lefteliflevelStart.rightisnotNone:levelStart=levelStart.rightelse:break# Constructed binary tree# 10# / \# 8 2# / /# 3 4if__name__=="__main__":root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.right.left=Node(4)connect(root)printLevels(root)
C#
usingSystem;usingSystem.Collections.Generic;publicclassNode{publicintdata;publicNodeleft,right,nextRight;publicNode(intkey){data=key;left=right=nextRight=null;}}classGFG{// Connect nodes using node count (level size)publicstaticNodeconnect(Noderoot){if(root==null)returnroot;Queue<Node>q=newQueue<Node>();q.Enqueue(root);while(q.Count>0){intnodeCount=q.Count;for(inti=0;i<nodeCount;i++){Nodenode=q.Dequeue();// Set nextRightif(i==nodeCount-1)node.nextRight=null;elsenode.nextRight=q.Peek();// Push childrenif(node.left!=null)q.Enqueue(node.left);if(node.right!=null)q.Enqueue(node.right);}}returnroot;}// Print level order using nextRight pointersstaticvoidprintLevels(Noderoot){NodelevelStart=root;while(levelStart!=null){Nodecurr=levelStart;while(curr!=null){Console.Write(curr.data+" ");curr=curr.nextRight;}Console.Write("# ");// Find the first node of the next levelif(levelStart.left!=null)levelStart=levelStart.left;elseif(levelStart.right!=null)levelStart=levelStart.right;elsebreak;}}publicstaticvoidMain(){// Constructed binary tree// 10// / \// 8 2// / /// 3 4Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root);}}
JavaScript
classNode{constructor(key){this.data=key;this.left=null;this.right=null;this.nextRight=null;}}// Connect nodes using node count (level size)functionconnect(root){if(!root)returnroot;letq=[root];while(q.length>0){letnodeCount=q.length;for(leti=0;i<nodeCount;i++){letnode=q.shift();// Set nextRightif(i===nodeCount-1)node.nextRight=null;elsenode.nextRight=q[0];// Push childrenif(node.left)q.push(node.left);if(node.right)q.push(node.right);}}returnroot;}// Print level order using nextRight pointersfunctionprintLevels(root){letlevelStart=root;while(levelStart!==null){letcurr=levelStart;while(curr!==null){console.log;// No operationprocess.stdout.write(curr.data+" ");curr=curr.nextRight;}process.stdout.write("# ");// Find the first node of the next levelif(levelStart.left!==null)levelStart=levelStart.left;elseif(levelStart.right!==null)levelStart=levelStart.right;elsebreak;}}// Driver code// Constructed binary tree// 10// / \// 8 2// / / // 3 4 // Driver Codeletroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root)
Output
10 # 8 2 # 3 4 #
[Expected Approach] Using Set Next Rights - O(n) Time and O(1) SpaceÂ
The idea is to use the previously set nextRight pointers to traverse each level and connect the children of its nodes to form the next level, without using a queue.
Set the root's nextRight pointer to NULL, as it has no node to its right.
Traverse the current level using the nextRight pointers.
For each node, connect its left child to its right child if both children exist.
If a child has no sibling to its right, use getNextRight() to find the next available child among the nodes to its right at the current level.
After processing the current level, move to the leftmost available node at the next level and repeat until all levels are connected.
The getNextRight() function searches the remaining nodes of the current level and returns the leftmost child it finds. If no such child exists, it returns NULL.
Consider Binary Tree:
Initially, all nextRight pointers are NULL.
Step 1: Node 10 has children 8 and 2. Connect them by setting 8.nextRight = 2.
Step 2:
Move to node 8. Its left child is 3, but it has no right child.
The getNextRight(8) function finds node 4, the left child of node 2. Connect 3.nextRight = 4.
Node 2 has no node to its right, so set 4.nextRight = NULL.
Step 3: Move to node 3. Nodes 3 and 4 have no children, so the process ends.
The final nextRight connections are:
C++
#include<iostream>usingnamespacestd;classNode{public:intdata;Node*left,*right,*nextRight;Node(intval){data=val;left=right=nextRight=nullptr;}};// Return the first node on the right// side of q and at the next levelNode*getNextRight(Node*p){Node*temp=p->nextRight;// Keep moving to next sibling until// you find a sibling that has at least// one childrenwhile(temp!=nullptr){if(temp->left!=nullptr)returntemp->left;if(temp->right!=nullptr)returntemp->right;temp=temp->nextRight;}returnnullptr;}// Function to connect nodes at the same levelNode*connect(Node*root){Node*temp;if(!root)returnnullptr;root->nextRight=nullptr;while(root!=nullptr){Node*q=root;// Traverse all nodes at the current levelwhile(q!=nullptr){if(q->left){if(q->right)q->left->nextRight=q->right;elseq->left->nextRight=getNextRight(q);}if(q->right)q->right->nextRight=getNextRight(q);q=q->nextRight;}// Move to the next level starting with the leftmost nodeif(root->left)root=root->left;elseif(root->right)root=root->right;elseroot=getNextRight(root);}returnroot;}// Print level order using nextRight pointersvoidprintLevels(Node*root){Node*levelStart=root;while(levelStart!=nullptr){Node*curr=levelStart;while(curr!=nullptr){cout<<curr->data<<" ";curr=curr->nextRight;}cout<<"# ";// Find the first node of the next levelif(levelStart->left!=nullptr)levelStart=levelStart->left;elseif(levelStart->right!=nullptr)levelStart=levelStart->right;elsebreak;}}intmain(){// Constructed binary tree// 10// / \ // 8 2// / / // 3 4 Node*root=newNode(10);root->left=newNode(8);root->right=newNode(2);root->left->left=newNode(3);root->right->left=newNode(4);connect(root);printLevels(root);return0;}
Java
classNode{publicintdata;publicNodeleft,right,nextRight;publicNode(intval){data=val;left=right=nextRight=null;}}publicclassGFG{// Return the first node on the right// side of q and at the next levelstaticNodegetNextRight(Nodep){Nodetemp=p.nextRight;// Keep moving to next sibling until// you find a sibling that has at least// one childrenwhile(temp!=null){if(temp.left!=null)returntemp.left;if(temp.right!=null)returntemp.right;temp=temp.nextRight;}returnnull;}// Function to connect nodes at the same levelstaticNodeconnect(Noderoot){Nodetemp;if(root==null)returnnull;root.nextRight=null;while(root!=null){Nodeq=root;// Traverse all nodes at the current levelwhile(q!=null){if(q.left!=null){if(q.right!=null)q.left.nextRight=q.right;elseq.left.nextRight=getNextRight(q);}if(q.right!=null)q.right.nextRight=getNextRight(q);q=q.nextRight;}// Move to the next level starting with the// leftmost nodeif(root.left!=null)root=root.left;elseif(root.right!=null)root=root.right;elseroot=getNextRight(root);}returnroot;}// Print level order using nextRight pointersstaticvoidprintLevels(Noderoot){NodelevelStart=root;while(levelStart!=null){Nodecurr=levelStart;while(curr!=null){System.out.print(curr.data+" ");curr=curr.nextRight;}System.out.print("# ");// Find the first node of the next levelif(levelStart.left!=null)levelStart=levelStart.left;elseif(levelStart.right!=null)levelStart=levelStart.right;elsebreak;}}publicstaticvoidmain(String[]args){// Constructed binary tree// 10// / \// 8 2// / /// 3 4Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root);}}
Python
classNode:def__init__(self,val):self.data=valself.left=self.right=self.nextRight=None# Return the first node on the right# side of q and at the next leveldefget_next_right(p):temp=p.nextRightwhiletempisnotNone:iftemp.leftisnotNone:returntemp.leftiftemp.rightisnotNone:returntemp.righttemp=temp.nextRightreturnNone# Function to connect nodes at the same leveldefconnect(root):ifrootisNone:returnNoneroot.nextRight=NonewhilerootisnotNone:q=rootwhileqisnotNone:ifq.leftisnotNone:ifq.rightisnotNone:q.left.nextRight=q.rightelse:q.left.nextRight=get_next_right(q)ifq.rightisnotNone:q.right.nextRight=get_next_right(q)q=q.nextRightifroot.leftisnotNone:root=root.leftelifroot.rightisnotNone:root=root.rightelse:root=get_next_right(root)returnroot# Print level order using nextRight pointersdefprintLevels(root):levelStart=rootwhilelevelStartisnotNone:curr=levelStartwhilecurrisnotNone:print(curr.data,end=" ")curr=curr.nextRightprint("#",end=" ")# Find the first node of the next leveliflevelStart.leftisnotNone:levelStart=levelStart.lefteliflevelStart.rightisnotNone:levelStart=levelStart.rightelse:breakif__name__=='__main__':# Constructed binary tree# 10# / \# 8 2# / /# 3 4root=Node(10)root.left=Node(8)root.right=Node(2)root.left.left=Node(3)root.right.left=Node(4)connect(root)printLevels(root)
C#
usingSystem;classNode{publicintdata;publicNodeleft,right,nextRight;publicNode(intval){data=val;left=right=nextRight=null;}}classGFG{// Return the first child on the right of p, at the next// levelstaticNodegetNextRight(Nodep){Nodetemp=p.nextRight;// Move to the next sibling until one has at least// one childwhile(temp!=null){if(temp.left!=null)returntemp.left;if(temp.right!=null)returntemp.right;temp=temp.nextRight;}returnnull;}// Connect nodes at the same levelstaticNodeconnect(Noderoot){if(root==null)returnnull;// Save the head, as root moves down the levelsNodehead=root;root.nextRight=null;while(root!=null){Nodeq=root;// Traverse all nodes at the current levelwhile(q!=null){if(q.left!=null){// Connect left child to right child,// else to the next available childif(q.right!=null)q.left.nextRight=q.right;elseq.left.nextRight=getNextRight(q);}// Connect right child to the next available// childif(q.right!=null)q.right.nextRight=getNextRight(q);q=q.nextRight;}// Move to the first node of the next levelif(root.left!=null)root=root.left;elseif(root.right!=null)root=root.right;elseroot=getNextRight(root);}returnhead;}// Print level order using nextRight pointersstaticvoidprintLevels(Noderoot){NodelevelStart=root;while(levelStart!=null){Nodecurr=levelStart;while(curr!=null){Console.Write(curr.data+" ");curr=curr.nextRight;}Console.Write("# ");// Find the first node of the next levelif(levelStart.left!=null)levelStart=levelStart.left;elseif(levelStart.right!=null)levelStart=levelStart.right;elsebreak;}}staticvoidMain(){// Constructed binary tree// 10// / \// 8 2// / /// 3 4Noderoot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root);}}
JavaScript
classNode{constructor(val){this.data=val;this.left=this.right=this.nextRight=null;}}// Return the first node on the right// side of q and at the next levelfunctiongetNextRight(p){lettemp=p.nextRight;while(temp!==null){if(temp.left!==null)returntemp.left;if(temp.right!==null)returntemp.right;temp=temp.nextRight;}returnnull;}// Function to connect nodes at the same levelfunctionconnect(root){if(root===null)returnnull;root.nextRight=null;while(root!==null){letq=root;while(q!==null){if(q.left!==null){if(q.right!==null)q.left.nextRight=q.right;elseq.left.nextRight=getNextRight(q);}if(q.right!==null)q.right.nextRight=getNextRight(q);q=q.nextRight;}if(root.left!==null)root=root.left;elseif(root.right!==null)root=root.right;elseroot=getNextRight(root);}returnroot;}// Print level order using nextRight pointersfunctionprintLevels(root){letlevelStart=root;while(levelStart!==null){letcurr=levelStart;while(curr!==null){console.log;// No operationprocess.stdout.write(curr.data+" ");curr=curr.nextRight;}process.stdout.write("# ");// Find the first node of the next levelif(levelStart.left!==null)levelStart=levelStart.left;elseif(levelStart.right!==null)levelStart=levelStart.right;elsebreak;}}// Driver code// Constructed binary tree// 10// / \// 8 2// / / // 3 4 letroot=newNode(10);root.left=newNode(8);root.right=newNode(2);root.left.left=newNode(3);root.right.left=newNode(4);connect(root);printLevels(root)