Java/c++/c solutions. Elegant iterative solutions (4 lines) and recursive solutions (5 lines)
C++\n## Recursive\nSetting the next pointer from the parent node makes for a clean solution. The only thing to worry about is how to handle the far right node o
# **C++**\n## Recursive\nSetting the _next_ pointer from the parent node makes for a clean solution. The only thing to worry about is how to handle the far right node of each level, which doesn\'t have a _next_. This is easy to check for too, just check if the parent node has a _next_ pointer, if it doesn\'t, then you\'re at the far right.\n```cpp\n  void connect(TreeLinkNode *root) {\n    if (root && root->left) {\n      root->left->next = root->right;\n      root->right->next = (root->next) ? root->next->left : nullptr;\n      connect(root->left);\n      connect(root->right);\n    }\n  }\n```\t\n## Iterative\nSet the _next_ pointer starting from the left of each level, then you can use the _next_ pointer to progress from left to right to complete the level. Once a level is finshed, advance down the left branch and do it again.\n```cpp\n  void connect(TreeLinkNode *root) {\n    for (; root && root->left; root = root->left) {\n      for (TreeLinkNode* pos = root; pos; pos = pos->next) {\n        pos->left->next = pos->right;\n        pos->right->next = (pos->next) ? pos->next->left : nullptr;\n      }\n    }\n  }\n```\t\n# **Java**\n## Recursive\n```java\n    public void connect(TreeLinkNode root) {\n      if (null != root && null != root.left) {\n        root.left.next = root.right;\n        root.right.next = (null != root.next) ? root.next.left : null;\n        connect(root.left);\n        connect(root.right);\n      }\n    }\n```\n## Iterative\n```java\n    public void connect(TreeLinkNode root) {\n      for (; null != root && null != root.left; root = root.left) {\n        for (TreeLinkNode pos = root; null != pos; pos = pos.next) {\n          pos.left.next = pos.right;\n          pos.right.next = (null != pos.next) ? pos.next.left : null;\n        }\n      }\n    }\n```\n# **C**\nSince a c solution would look very much like the c++ solution, I did it slightly differently, but is essentially the same.\n```c\nstruct Node* connect(struct Node* root) {\n  if (root) {\n    for (struct Node* row_start = root; row_start->left; row_start = row_start->left) {\n      struct Node* pos = row_start;\n      for (; pos->next; pos = pos->next) {\n        pos->left->next = pos->right;\n        pos->right->next = pos->next->left;\n      }\n      pos->left->next = pos->right;\n    }\n  }\n  return root;\n}\n```\n\n**Note that all solutions abuse the fact that the tree is by definition a perfect binary tree. [Solutions that don\'t require perfect tree can be found here](https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/163809/C++-iterative-O(1)-space.-Short-and-easy-to-understand-with-detail.-Bonus-2-line-solution-for-fun)**\n
['C', 'Java']