1 /**
2 * Definition for binary tree with next pointer.
3 * struct TreeLinkNode {
4 * int val;
5 * TreeLinkNode *left, *right, *next;
6 * TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
7 * };
8 */
9 class Solution {
10 public:
11 void connect(TreeLinkNode *root) {
12 // Note: The Solution object is instantiated only once and is reused by each test case.
13 if (root==NULL || root->left==NULL || root->right==NULL)
14 return;
15 root->left->next = root->right;
16 if (root->next!=NULL)
17 root->right->next=root->next->left;
18 connect(root->left);
19 connect(root->right);
20 }
21 };