Very simple iterative and recursive solutions yet still accepted as best in cpp


  • 2
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            TreeLinkNode *cur, head(0);
            while(root)
            {
                head.next = NULL;
                cur = &head;
                while(root)
                {
                    if(root->left)
                    {
                        cur->next = root->left;
                        cur = cur->next;
                    }
                    if(root->right)
                    {
                        cur->next = root->right;
                        cur = cur->next;
                    }
                    root = root->next;
                }
                root = head.next;
            }
        }
    };

  • 0

    Enclosed with a <font color="#ff0000">recursive solution</font> here for completeness.

    class Solution {
    public:
        //Always remember to use header when it comes to collecting linked list;
        //AC - recursive method - 40ms;
        void connect(TreeLinkNode *root) 
        {
            if(!root) return ;
            TreeLinkNode t(0), *cur;
            cur = &t;
            while(root)
            {
                if(root->left)
                {
                    cur->next = root->left;
                    cur = cur->next;
                }
                if(root->right)
                {
                    cur->next = root->right;
                    cur = cur->next;
                }
                root = root->next;
            }
            connect(t.next);
        }
    };

Log in to reply
 

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