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

Populating Next Right Pointers in Each Node II

2015-06-12 20:59 609 查看
class Solution {

public:

void connect(TreeLinkNode *root) {

int flag=0;

TreeLinkNode* p;

if(!root) return;

if(root->left&&root->right) root->left->next=root->right;

if(root->next)

{

if(!root->next->left&&!root->next->right)

{

if(root->next->next) p=root->next, root->next=root->next->next,flag=1;

}

if((root->right||root->left)&&(root->next->right||root->next->left)) //两个接上

{

if(root->right&&root->next->left) root->right->next=root->next->left;

if(root->right&&!root->next->left) root->right->next=root->next->right;

if(!root->right&&root->next->left) root->left->next=root->next->left;

if(!root->right&&!root->next->left) root->left->next=root->next->right;

}

if(flag==1)

{

p->next=root->next->next;

root->next=p->next;

flag=0;

}

}//判断root->right是否为空;

connect(root->left);

connect(root->right);

}

};

class Solution {

public:

void connect(TreeLinkNode *root)

{

if(root == NULL)

return ;

TreeLinkNode *next_level_first = NULL;//下一层的首结点

TreeLinkNode *next_level_cur = NULL;//下一层的当前结点

//每个while循环遍历一层,并且找出下一层的首结点

while(root != NULL)

{

if(next_level_first == NULL)

next_level_first = root->left ? root->left : root->right; //开始写成了next_level_first = root->right ? root->right : root->left;,都哭了

//如果当前结点的左孩子存在,且前一个结点存在,则把左孩子置为前一个结点的next

if(root->left != NULL)

{

if(next_level_cur != NULL)

next_level_cur->next = root->left;

next_level_cur = root->left;//包含两个意思,1.当next_level_cur为空时,把root->left结点作为当前结点 2.当前结点不为空时,经过上面if的处理后,把当前结点的next作为当前结点,即当前结点向后挪一位

}

//对右结点做相同的处理

if(root->right != NULL)

{

if(next_level_cur != NULL)

next_level_cur->next = root->right;

next_level_cur = root->right;

}

root = root->next;//root向后挪一位,处理root的孩子结点

}

connect(next_level_first);//把上面循环保存的下一层首结点赋给root,向下一层,继续遍历

}

};

某人的方法,其实用层序遍历应该是挺简答 的
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: