https://leetcode.com/problems/populating-next-right-pointers-in-each-node


Runtime: 24 ms, faster than 29.70% of C++ online submissions for Populating Next Right Pointers in Each Node.
Memory Usage: 18.2 MB, less than 5.91% of C++ online submissions for Populating Next Right Pointers in Each Node.



```cpp
 class Solution {
public:
    Node* connect(Node* root) {
      //5:43
      if (root == nullptr) {
        return nullptr;
      }

      vector<vector<Node*>> level_list;
      level_list.push_back(vector<Node*>{root});

      while (true) {
        //auto current_level = *level_list.end();
        auto current_level = *(level_list.end()-1);
        //auto current_level = level_list[level_list.size() - 1];
        level_list.push_back(vector<Node*>{});

        for (auto each : current_level) {
          if (each->left != nullptr) {
            level_list[level_list.size() - 1].push_back(each->left);
            //(*level_list.end()).push_back(each->left);
          }
          if (each->right != nullptr) {
            level_list[level_list.size() - 1].push_back(each->right);
            //(*level_list.end()).push_back(each->right);
          }
        }

        if (level_list[level_list.size() - 1].size() == 0) {
          level_list.pop_back();
          break;
        }
      }

      for (auto each_level : level_list) {
        for (int i=0; i < each_level.size(); i++) {
          if (i == each_level.size()-1) {
            each_level[i]->next = nullptr;
          } else {
            each_level[i]->next = each_level[i+1];
          }
        }
      }

      return level_list[0][0];
      //5:50
    }
};
```