/**
* 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 == NULL)
return ;
int cnt = 1;
queue<TreeLinkNode*> a[2];
a[1].push(root);
while (a[0].size() || a[1].size())
{
while (a[cnt].size())
{
root = a[cnt].front();
a[cnt].pop();
if (root->left)
a[(cnt + 1) % 2].push(root->left);
if (root->right)
a[(cnt + 1) % 2].push(root->right);
if(a[cnt].size())
root->next = a[cnt].front();
else
root->next = NULL;
}
cnt = (cnt + 1) % 2;
}
}
};
level遍历117. Populating Next Right Pointers in Each Node II
最新推荐文章于 2017-01-21 22:54:56 发布