描述
给出一棵树,把每一层的节点连接起来
解决
利用queue存每一层的节点,然后遍历即可。
/**
* 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:
void connect(TreeLinkNode *root) {
if (!root)
return ;
queue<TreeLinkNode *> que;
que.push(root);
root -> next = NULL;
int cnt = 1;
while (!que.empty())
{
TreeLinkNode *zz = NULL;
int t = 0;
for (int i = 0; i < cnt; ++i)
{
TreeLinkNode *tmp = que.front();
//cout << tmp -> val << endl;
que.pop();
if (tmp -> left)
{
que.push(tmp -> left);
++t;
}
if (tmp -> right)
{
que.push(tmp -> right);
++t;
}
if (i == 0)
{
zz= tmp;
continue;
}
else if (i != cnt - 1)
{
zz -> next = tmp;
zz = tmp;
}
else if (i == cnt - 1)
{
zz -> next = tmp;
tmp -> next = NULL;
}
}
cnt = t;
}
return ;
}
};