O(1) space with two loops


  • 0
    G

    Inspired by this post,

    1. i iterates all levels, like the row index
    2. j iterates each level, like the column index
    class Solution {
     public:
      void connect(TreeLinkNode* root) {
        for (TreeLinkNode* i = root; i; i = i->left) {
          if (!i->left) break;
          for (TreeLinkNode *j = i; j; j = j->next) {
            j->left->next = j->right;
            if (j->next)
              j->right->next = j->next->left;
          }
        }
      }
    };
    

Log in to reply
 

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