Clear C++ O(1) Space


  • 3
    F
    class Solution {
    public:
        void connect(TreeLinkNode *root) { //O(1) space
            while (root)
            {
                TreeLinkNode * pre = nullptr;
                 for (auto cur = root; cur; cur=cur->next)
                 {
                     if (cur->left)
                     {
                         if (pre == nullptr)
                             root = cur->left;
                         else
                             pre->next = cur->left;
                         pre = cur->left;
                     }
                     if (cur->right)
                     {
                         if (pre == nullptr)
                             root = cur->right;
                         else
                             pre->next = cur->right;
                         pre = cur->right;
                     }
                 }
                 if (pre == nullptr) //No next root found.
                    break;
            }
        }
    };

Log in to reply
 

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