2020.10.15第一次解答:
解题思路
依然是中序遍历,采用一个辅助队列存储每一层的结点,依次连接即可
C++代码
/*
// 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:
Node* connect(Node* root) {
if (!root || !root->left) return root;
queue<Node*> q;
q.push(root->left);
q.push(root->right);
int times = 2;
while (!q.empty()) {
Node* cur = q.front();
Node* next = NULL;
q.pop();
if (cur->left) {
q.push(cur->left);
q.push(cur->right);
}
for (int i = 1; i < times; i++) {
if (!q.empty()) {
next = q.front();
q.pop();
if (next->left) {
q.push(next->left);
q.push(next->right);
}
}
cur->next = next;
cur = cur->next;
}
times *= 2;
}
return root;
}
};