Populating Next Right Pointers in Each Node II
https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/description/
Thoughts
Code
/*
* @lc app=leetcode id=117 lang=cpp
*
* [117] Populating Next Right Pointers in Each Node II
*/
// @lc code=start
/*
// Definition for a Node.
class Node {
public:
int val;
Node* left;
Node* right;
Node* next;
Node() {}
Node(int _val, Node* _left, Node* _right, Node* _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public:
Node* connect(Node* root) {
Node *cur = root, *pre_c = nullptr, *next_lev = nullptr;
const auto conn = [&](Node *l) {
if (l == nullptr) return;
if (next_lev == nullptr) next_lev = l;
if (pre_c != nullptr) pre_c->next = l;
pre_c = l;
};
while (cur != nullptr) {
conn(cur->left);
conn(cur->right);
if (cur->next == nullptr) {
cur = next_lev;
next_lev = nullptr;
pre_c = nullptr;
} else cur = cur->next;
}
return root;
}
};
// @lc code=end
Analysis
Last updated