Simple C++ solution beating 88%


  • 0
    L

    The idea is simple, store a dummy header to the next level, and use a prev variable to simplify the linking process. The original idea is from here

    void connect(TreeLinkNode *root) {
          
          auto cur = root;
          while (cur!= nullptr)
          {
              
              TreeLinkNode nextLevelHead(-1);
              TreeLinkNode* prev = &nextLevelHead;
              for (auto node = cur; node!=nullptr; node=node->next)
              {
                  if (node->left!=nullptr)
                  {
                      prev->next = node->left;
                      prev = prev->next;
                  }
                  
                  if (node->right !=nullptr)
                  {
                      prev->next = node->right;
                      prev = prev->next;
                  }
              }
              cur = nextLevelHead.next;
          }
        }
    

Log in to reply
 

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