Connect Nodes at Same Level | Practice | GeeksforGeeks

Given a binary tree, connect the nodes that are at same level. You'll be given an addition nextRight pointer for the same.
Initially, all the nextRight pointers point to garbage values. Your function should set these pointers to point next right for each node.
       10                       10 ------> NULL
      / \                       /      \
     3   5       =>     3 ------> 5 --------> NULL
    / \     \               /  \           \
   4   1   2          4 --> 1 -----> 2 -------> NULL
 
Example 1:
Input:
     3
   /  \
  1    2
Output:
3 1 2
1 3 2
Explanation:The connected tree is
        3 ------> NULL
     /    \
    1-----> 2 ------ NULL

Example 2:
Input:
      10
    /   \
   20   30
  /  \
 40  60
Output:
10 20 30 40 60
40 20 60 10 30
Explanation:The connected tree is
         10 ----------> NULL
       /     \
     20 ------> 30 -------> NULL
  /    \
 40 ----> 60 ----------> NULL
Your Task:
You don't have to take input. Complete the function connect() that takes root as parameter and connects the nodes at same level. The printing is done by the driver code. First line of the output will be level order traversal and second line will be inorder travsersal
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 ≤ Number of nodes ≤ 105
0 ≤ Data of a node ≤ 105
0
cs20015in 7 hours
 void connect(Node *root)   {          queue<Node*>q;    q.push(root);    while(!q.empty()){        int n = q.size();        for(int i= 0; i<n; i++){            Node*temp = q.front();            q.pop();            if(q.empty())            temp->nextRight=NULL;             else{                 temp->nextRight = q.front();             }                        if(temp->left)            q.push(temp->left);            if(temp->right);            q.push(temp->right);                                }                        }                       }         }; 
 
0
lokeshdohare1231 day ago
JAVA Code:
 
public void connect(Node node)   {              Queue<Node> q = new LinkedList<>();       q.add(node);       int len=0;       while(!q.isEmpty())       {           ArrayList<Node> temp = new ArrayList<Node>();           len=q.size();           for(int i=0;i<len;i++)           {               Node curr = q.remove();               temp.add(curr);               if(curr.left!=null)                   q.add(curr.left);               if(curr.right!=null)                   q.add(curr.right);           }           for(int i=0;i<temp.size();i++)           {               if(i==(temp.size()-1))               {                   (temp.get(i)).nextRight=null;               }               else               {                   (temp.get(i)).nextRight = temp.get(i+1);               }           }       }   }
0
rmn51243 days ago
class Solution
{
    public:
    //Function to connect nodes at same level.
    void connect(Node *p)
    {
       queue< Node * > qq;
   qq.push(p);
   while(!qq.empty()){
       int sz = qq.size();
       while(sz > 0){
           Node* node = qq.front();
           qq.pop();
          
           if(sz > 1){
               node->nextRight = qq.front();
           }else{
               node->nextRight = NULL;
           }
           if(node->left != NULL)
           qq.push(node->left);
           if(node->right != NULL)
           qq.push(node->right);
           sz--;
       }
    }
    }
      
};
0
dharpranoy22555 days ago
Solution
 
LinkedList<Node> que = new LinkedList<>();       que.add(root);       while (que.isEmpty()==false){         int n=que.size();           for (int i=0;i<n;i++){               Node cur = que.poll();               if (i==n-1){                   cur.nextRight=null;               }else{                   cur.nextRight=que.get(0);               }               if (cur.left!=null){                   que.add(cur.left);               }               if (cur.right!=null){                   que.add(cur.right);               }           }       }
0
hr061 week ago
class Solution
{
   public:
   //Function to connect nodes at same level.
   void connect(Node *root)
   {
      // Your Code Here
      if(!root)
      {
          return;
      }
   
       // we use queue for level order traversal
      queue<Node*> q;
      q.push(root);
      
       while(!q.empty())
       {
           int size = q.size();
           while(size--)
           {
               Node* frontNode = q.front();
               q.pop();
               if(!size) frontNode->nextRight = NULL;
                 
               else frontNode->nextRight = q.front();
                 
               if(frontNode->left) q.push(frontNode->left);
                 
               if(frontNode->right) q.push(frontNode->right);
   
           }
   
       }
   }    
     
};

0
srujugowda4561 week ago
C++ solution using level order traversal
class Solution
{
    public:
    //Function to connect nodes at same level.
    void connect(Node *root)
    {
       queue<Node*> q;
       q.push(root);
       
       while(!q.empty()){
           int size=q.size();
           for(int i=0;i<size;i++){
               Node* temp=q.front();
               q.pop();
               if(q.empty() || i==size-1){
                   temp->nextRight=NULL;
               }else{
                   temp->nextRight=q.front();
               }
               
               if(temp->left){
                   q.push(temp->left);
               }
               if(temp->right){
                   q.push(temp->right);
               }
           }
       }
    }    
      
};
0
anugrahlko1 week ago
class Solution{   //Function to connect nodes at same level.   static HashMap<Integer, ArrayList<Node>> map;   public void connect(Node root)   {       int level=0;       map = new HashMap<Integer, ArrayList<Node>>();       leveOrderTraversal(root, level, map);       int i=0;       while(map.containsKey(i)){           ArrayList<Node> a = map.get(i);            int j;            for( j=0;j<a.size()-1;j++){                a.get(j).nextRight =a.get(j+1);            }            a.get(j).nextRight = null;            i++;       }   }   static void leveOrderTraversal(Node node,int l,HashMap<Integer, ArrayList<Node>> map){       if(node==null)return;       if(map.containsKey(l)){           ArrayList<Node> arr= map.get(l);           arr.add(node);           map.put(l,arr);       }else{           ArrayList<Node> arr= new ArrayList<Node>();           arr.add(node);           map.put(l,arr);       }       leveOrderTraversal(node.left, l+1, map);       leveOrderTraversal(node.right, l+1, map);   }}
+1
suhitgupta1112 weeks ago
class Solution{   //Function to connect nodes at same level.   public void connect(Node root)   {       // Your code goes here.       if(root==null) return;       Queue<Node> q = new LinkedList<>();       q.add(root);       while(!q.isEmpty()){           int size=q.size();           for(int i=0;i<size;i++){               Node curr=q.poll();               if(curr.left!=null)  q.add(curr.left);               if(curr.right!=null) q.add(curr.right);               if(i!=size-1)  curr.nextRight=q.peek();           }       }   }}
0
amankumar2783 weeks ago
Java Solution: using QUEUE
class Solution{        //Function to connect nodes at same level.   public void connect(Node root)   {        if(root==null){           return ;       }       Queue<Node> q=new LinkedList<>();       q.add(root);       int curr=1;       int next=0;       while(curr!=0){            Node temp=q.poll();           if(temp.left!=null){               q.add(temp.left);               next++;           }           if(temp.right!=null){               q.add(temp.right);               next++;           }           if(curr>1){               temp.nextRight=q.peek();           }else{               temp.nextRight=null;           }           curr--;           if(curr==0){               curr=next;               next=0;           }       }                 }}
0
harshrauth3 weeks ago
class Solution{   public:   //Function to connect nodes at same level.   void connect(Node *root)   {      // Your Code Here      queue<Node*>q;      q.push(root);      q.push(NULL);      while(!q.empty())      {          if(q.front()!=NULL)          {               Node * temp=q.front();               q.pop();               temp->nextRight=q.front();               if(temp->left!=NULL)                   q.push(temp->left);               if(temp->right!=NULL)                   q.push(temp->right);          }          else          {              if(q.size()!=1)                   q.push(NULL);              q.pop();          }                }   }         };
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
                    want to view the editorial?
 Login to access your submissions. 

Problem


Contest

Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab.