思路:
- 层次遍历二叉树
-
代码:
```cpp / // Definition for a Node. class Node { public: int val; Node left; Node right; Node next;
Node() : val(0), left(NULL), right(NULL), next(NULL) {}
Node(int _val) : val(_val), left(NULL), right(NULL), next(NULL) {}
Node(int _val, Node _left, Node _right, Node* _next)
: val(_val), left(_left), right(_right), next(_next) {}
}; */
class Solution {
public:
void levelConnect(vector
Node* connect(Node* root) {
if (!root) {
return root;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
vector<Node*> nodes;
int cur_level_size = q.size();
for (int i = 0; i < cur_level_size; ++i) {
Node* cur_node = q.front();
q.pop();
nodes.push_back(cur_node);
if(cur_node->left) q.push(cur_node->left);
if(cur_node->right) q.push(cur_node->right);
}
levelConnect(nodes, cur_level_size);
}
return root;
}
}; ```