描述
把每层的节点连接起来,要求O(1)的空间
解决
不会,看了这个算法写的,利用一个辅助节点记录每一层的开始节点
/**
* 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 ;
while (root)
{
TreeLinkNode temp(-1);
TreeLinkNode *zz = &temp;
while (root)
{
if (root -> left)
{
zz -> next = root -> left;
zz = zz -> next;
}
if (root -> right)
{
zz -> next = root -> right;
zz = zz -> next;
}
root = root -> next;
}
root = temp.next;
}
return ;
}
};