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

leetcode Populating Next Right Pointers in Each Node

2017-02-01 22:21 411 查看
这道题直观的思路是采用层序遍历,在每次换行的时候进行一次处理,不换行的时候直接连接当前节点和他右边的兄弟即可,使用两个变量来标示换行。

/**
* 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) {
int nextLevel = 0;       //下一层需要访问几个节点
int tobePrint = 1;      //还需访问几个节点
queue<TreeLinkNode*> q;
if(root == NULL)
return;
q.push(root);
while(!q.empty())
{
TreeLinkNode* curNode = q.front();
if(curNode -> left != NULL)
{
nextLevel++;
q.push(curNode -> left);
}
if(curNode -> right != NULL)
{
nextLevel++;
q.push(curNode -> right);
}
q.pop();
tobePrint--;
if(tobePrint == 0) //当前行的最后一个节点
{
curNode -> next = NULL;
tobePrint = nextLevel;
nextLevel = 0;
}
else
{
curNode -> next = q.front();
}
}
}

};


Not signed i

Not signed i
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode