Leetcode 117 Solution

This article provides solution to leetcode question 117 (populating-next-right-pointers-in-each-node-ii)

https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii

Solution

/**
 * Definition for binary tree with next pointer.
 * struct TreeLinkNode {
 *  int val;
 *  TreeLinkNode *left, *right, *next;
 *  TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
 * };
 */
class Solution {
public:
    void connect(TreeLinkNode *root) {
        if (root == NULL)
            return;

        TreeLinkNode* p = root;

        while (p)
        {
            TreeLinkNode dummyNode(0);
            TreeLinkNode* q = &dummyNode;

            while (p)
            {
                if (p->left)
                    q->next = p->left, q = q->next;
                if (p->right)
                    q->next = p->right, q = q->next;

                p = p->next;
            }

            p = dummyNode.next;
        }
    }
};