My simple C++ code

  • 2
    class Solution {
        void connect(TreeLinkNode *root) {
            TreeLinkNode *parentHead = root;
            TreeLinkNode *curPNode, *curCNode;
            {// in this loop, invariant fact is the parent node next link is connected already, we just need to connect the children node next link.
                curPNode = parentHead; // current parent node
                curCNode = curPNode->left; // current child node
                while(curPNode && curPNode->left) 
                { // if the current parent node has children
                    curCNode->next       = curPNode->left;
                    curCNode->next->next = curPNode->right;
                    curCNode =  curPNode->right;
                    curPNode = curPNode->next;
                parentHead = parentHead->left; // update the parent-node next-link list header

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.