您的位置:首页 > Web前端 > Node.js

LC117 Populating Next Right Pointers in Each Node II

2016-07-28 09:46 696 查看
这道题目关键是先得到上下两层的起始节点,然后分几种情况分别处理:1.下层节点是上层节点的左子节点,且上层节点的右子节点非空。2.下层节点是上层节点的左子节点且上层节点的右子节点为空,或者下层节点是上层节点的右子节点。3.上层节点没有孩子。 分清楚了情况就简单了。

class Solution {
public:
void _connect(TreeLinkNode* root)
{
TreeLinkNode* tmp = NULL;
TreeLinkNode* head = root;
while(root!=NULL&&root->left==NULL&&root->right==NULL)
root=root->next;
if(root==NULL)
return;
if(root->left!=NULL)
tmp=root->left;
else
tmp=root->right;
TreeLinkNode* record=tmp;
while(root!=NULL)
{
if(tmp==root->left&&root->right!=NULL)
{
tmp->next=root->right;
tmp=root->right;
root=root->next;
}
else if((tmp==root->left&&root->right==NULL)||(tmp==root->right))
{
root=root->next;
}
else
{
if(root->left!=NULL)
{
tmp->next=root->left;
tmp=tmp->next;
}
else if(root->right!=NULL)
{
tmp->next=root->right;
tmp=tmp->next;
root=root->next;
}
else
root=root->next;
}
}
_connect(record);
}
void connect(TreeLinkNode *root) {
if(root==NULL)
return;
_connect(root);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: