Simple C++ solution using iteration, 24ms, O(N) time, O(1) space


  • 1
    J
    class Solution {
    public:
        void connect(TreeLinkNode *root) {
            if (!root) return;
            TreeLinkNode* seed = root;
            seed->next = NULL;
            while (seed->left)
            {
                TreeLinkNode* worker = seed;
                while (worker->next)
                {
                    worker->left->next = worker->right;
                    worker->right->next = worker->next->left;
                    worker = worker->next;
                }
                worker->left->next = worker->right;
                worker->right->next = NULL;
                seed = seed->left;
            }
        }
    };

Log in to reply
 

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