Skip to content

Latest commit

 

History

History
49 lines (43 loc) · 1.06 KB

File metadata and controls

49 lines (43 loc) · 1.06 KB

Screen Shot Screen Shot

/*
// 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 nullptr;

        Node* curr = root;
        while(curr) {
            Node dummy(0);
            Node* tail = &dummy;
            Node* p = curr;
            while(p) {
                if(p->left) {
                    tail->next = p->left;
                    tail = tail->next;
                }
                if(p->right) {
                    tail->next = p->right;
                    tail = tail->next;
                }
                p = p->next;
            }
            curr = dummy.next;
        }

        return root;
    }
};