It is very natural to promote it. What if we get rid of the condition of a Complete Binary Tree? Because this condition is not critical, it will not affect the overall thinking. The practice is to find the starting point of each layer, and then step by layer.
If it is a Complete Binary Tree, the starting point of each layer is the left child of the upper starting point. The links between brothers are also simple. You can directly find the right and right children of the corresponding father. Generally, the starting point of a binary tree is the first left child with a child node on the upper layer, or the right child without a left child. In order to be continuously linked in the child layer, we must save it as the previous node of the Child layer. When the current layer finds a node with a child, it is connected to the back of the pre node, then update the pre node's point.
class Solution {public: void connect(TreeLinkNode *root) { if(root == NULL) return; TreeLinkNode *beginNode = root, *leftNode, *pre; while(beginNode){ leftNode = beginNode; pre = NULL; beginNode = NULL; while(leftNode){ if(leftNode->left&&leftNode->right){ leftNode->left->next = leftNode->right; if(pre) pre->next = leftNode->left; if(!beginNode) beginNode = leftNode->left; pre = leftNode->right; }else if(leftNode->left){ if(pre) pre->next = leftNode->left; if(!beginNode) beginNode = leftNode->left; pre = leftNode->left; }else if(leftNode->right){ if(pre) pre->next = leftNode->right; if(!beginNode) beginNode = leftNode->right; pre = leftNode->right; } leftNode = leftNode->next; } } }};