Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- // Definition for a Node.
- class Node {
- public:
- int val;
- Node* left;
- Node* right;
- Node* next;
- Node() : val(0), left(NULL), right(NULL), next(NULL) {}
- Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
- Node(int _val, Node* _left, Node* _right, Node* _next)
- : val(_val), left(_left), right(_right), next(_next) {}
- };
- */
- class Solution {
- public:
- Node* connect(Node* root) {
- if(!root) return root;
- root->next = nullptr;
- Node *parentLeftMost = root;
- //parent level is sorted
- while(1){
- while(parentLeftMost && !parentLeftMost->left && !parentLeftMost->right){
- parentLeftMost = parentLeftMost->next;
- }
- if(!parentLeftMost){
- //i.e there is no next level
- return root;
- }
- Node *upcomingParentLeftMost = parentLeftMost->left ? parentLeftMost->left : parentLeftMost->right; //refers to the leftmost node of next level. Will be the next parentLeftMost
- Node *tempP = parentLeftMost;
- Node *tempC = upcomingParentLeftMost;
- while(1){
- Node *toAttach = nullptr;
- if(tempP->right != nullptr && tempP->right!= tempC){
- toAttach = tempP->right;
- }
- else{
- while(tempP->next != nullptr && toAttach == nullptr){
- tempP = tempP->next;
- toAttach = tempP->left ? tempP->left : tempP->right;
- }
- }
- tempC->next = toAttach;
- tempC = tempC->next;
- if(tempC == nullptr){
- parentLeftMost = upcomingParentLeftMost;
- break;
- }
- }
- }
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement