题目描述:
方法一:
首先想到层级遍历,既然是层级遍历,心想没准之前102的函数可以拿来用于【斜眼笑】,于是写了这么个不伦不类的算法:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
vector<vector<TreeLinkNode*> > result;
void LevelOrderTraversal(TreeLinkNode* root, int level)
{
if(!root) return;
if(result.size() == level)
result.push_back(vector<TreeLinkNode*>());
result[level].push_back(root);
LevelOrderTraversal(root->left, level+1);
LevelOrderTraversal(root->right, level+1);
}
void connect(TreeLinkNode *root) {
LevelOrderTraversal(root, 0);
for(int i=0; i<result.size(); i++)
{
for(int j=0; j<result[i].size()-1; j++)
{
result[i][j]->next = result[i][j+1];
result[i][result[i].size()-1]->next = NULL;
}
}
}
};
果然可以,结果还不错
方法二:
正常的队列层级遍历做法:
/**
* Definition for binary tree with next pointer.
* struct TreeLinkNode {
* int val;
* TreeLinkNode *left, *right, *next;
* TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
* };
*/
class Solution {
public:
queue<TreeLinkNode* > q;
void connect(TreeLinkNode *root) {
if(root == NULL)return;
q.push(root);
while(!q.empty())
{
int n = q.size();
TreeLinkNode* tmp;
TreeLinkNode* cur;
tmp = q.front();
q.pop();
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
for(int i=0; i<n-1; i++)
{
cur = q.front();
q.pop();
tmp->next = cur;
tmp = cur;
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
}
tmp->next = NULL;
}
}
};
上面的两种方法都只是24ms,并不是最快,于是在题解中找到了16ms的solution:
class Solution {
public:
void connect(TreeLinkNode *root) {
if (!root) return;
queue<TreeLinkNode*> que;
que.push(root);
while (que.size() > 0) {
int size = que.size();
for (int i = 0; i < size; i++) {
TreeLinkNode* node = que.front();
que.pop();
node->next = (i==size-1)?nullptr:que.front();
if ( node->left ) que.push(node->left);
if ( node->right ) que.push(node->right);
}
}
}
};