/**
* 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;
TreeLinkNode *pNode=root;
while(pNode)
{
TreeLinkNode *nextLevel=0;
TreeLinkNode *prev=0;
for(;pNode;pNode=pNode->next)
{
if(!nextLevel) nextLevel=(pNode->left?pNode->left:pNode->right);
if(pNode->left)
{
if(prev)
{
prev->next=pNode->left;
}
prev=pNode->left;
}
if(pNode->right)
{
if(prev)
{
prev->next=pNode->right;
}
prev=pNode->right;
}
}
pNode=nextLevel;
}
}
};
Populating Next Right Pointers in Each Node II
最新推荐文章于 2022-04-05 16:12:16 发布