My solution with O(1) space and O(n) time, anyone has simpler code?


  • 3
    P

    This is my code. Is there any simpler solution?

    void connect(TreeLinkNode *root) {
        if (root == NULL) return;
        TreeLinkNode * start = root;
        TreeLinkNode * end = root;
        TreeLinkNode * levelEnd = root;
        while (start != NULL)
        {
            if (start->left != NULL)
            {
                end->next = start->left;
                end = end->next;
            }
            if (start->right != NULL)
            {
                end->next = start->right;
                end = end->next;
            }
            if (start == levelEnd)
            {
                start = start->next;
                levelEnd->next = NULL;
                levelEnd = end;
            }
            else
            {
                start = start->next;
            }
        }
    }

  • 0
    H

    thanks for your post, this code is very nice!


Log in to reply
 

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