题目地址: https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
关键思路:讲节点的左右子节点链接起来,遍历节点的next节点,即可。
class Solution {
public:
TreeLinkNode* gethead(TreeLinkNode* root)
{
if(root == NULL)
return NULL;
if(root->left != NULL)
return root->left;
else
return root->right;
} TreeLinkNode* gettail(TreeLinkNode* root)
{
if(root == NULL)
return NULL;
if(root->right != NULL)
return root->right;
else
return root->left;
} void connect(TreeLinkNode *root)
{
TreeLinkNode* head = NULL;
TreeLinkNode* tail = NULL;
if(root == NULL)
return; TreeLinkNode* pcur = root;
while(root != NULL)
{
TreeLinkNode* headtmp = gethead(root);
TreeLinkNode* tailtmp = gettail(root); if(headtmp == NULL)
{
root= root->next;
continue;
} if(headtmp != tailtmp)
headtmp->next = tailtmp; if(tail != NULL)
{
tail->next = headtmp;
tail = tailtmp;
}
else
{
head = headtmp;
tail = tailtmp;
}
root = root->next;
} while(pcur != NULL)
{
TreeLinkNode* tmp = gethead(pcur);
if(tmp != NULL)
{
connect(tmp);
break;
}
pcur = pcur->next;
}
} };