Advertisement
imashutosh51

Connect Nodes at same level

Jul 23rd, 2022 (edited)
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.76 KB | None | 0 0
  1. //Logic :used BFS,stored nodes in the deque and made all same layer node's nextright node to right adjacent node of same layer.
  2. //TC O(N) traversed all node once
  3. class Solution
  4. {
  5.     public:
  6.     //Function to connect nodes at same level.
  7.     void connect(Node *root){
  8.        if(!root) return;
  9.        deque<Node*> q;
  10.        q.push_back(root);
  11.        while(!q.empty()){
  12.            int k=q.size();
  13.            for(int i=0;i<k;i++){
  14.                Node *temp=q.front();
  15.                q.pop_front();
  16.                if(i==k-1) temp->nextRight=NULL;
  17.                else if(q.size()) temp->nextRight=q.front();
  18.                if(temp->left) q.push_back(temp->left);
  19.                if(temp->right) q.push_back(temp->right);
  20.            }
  21.        }
  22.     }    
  23.      
  24. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement