Leetcode 116 Solution

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

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

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) { auto p = root;
while (p) { TreeLinkNode dummyhead(0); TreeLinkNode* q = &dummyhead;
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 = dummyhead.next; } } };