Advertisement
nikunjsoni

117

May 9th, 2021
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.95 KB | None | 0 0
  1. /*
  2. // Definition for a Node.
  3. class Node {
  4. public:
  5.     int val;
  6.     Node* left;
  7.     Node* right;
  8.     Node* next;
  9.  
  10.     Node() : val(0), left(NULL), right(NULL), next(NULL) {}
  11.  
  12.     Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
  13.  
  14.     Node(int _val, Node* _left, Node* _right, Node* _next)
  15.         : val(_val), left(_left), right(_right), next(_next) {}
  16. };
  17. */
  18.  
  19. class Solution {
  20. public:
  21.     Node* connect(Node* root) {
  22.         if(!root) return NULL;
  23.         auto head = root;
  24.        
  25.         while(root){
  26.             Node *tmpChild = new Node(0);
  27.             Node *nextLevel = tmpChild;
  28.             while(root){
  29.                 if(root->left) {tmpChild->next = root->left; tmpChild = tmpChild->next;}
  30.                 if(root->right) {tmpChild->next = root->right; tmpChild = tmpChild->next;}
  31.                 root = root->next;
  32.             }
  33.             root = nextLevel->next;
  34.         }
  35.        
  36.         return head;
  37.     }
  38. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement