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

LeetCode116—Populating Next Right Pointers in Each Node

2016-04-09 20:44 661 查看

LeetCode116—Populating Next Right Pointers in Each Node

原题

Given a binary tree

struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}


Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

You may only use constant extra space.

You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,

Given the following perfect binary tree,

         1

        /  \

       2    3

      /   \  /   \

     4    5 6    7

After calling your function, the tree should look like:

       1 -> NULL

      /    \

     2  ->   3 -> NULL

    /  \    /   \

   4 ->5 ->6 -> 7 -> NULL

分析

就是把完全二叉树的连起来,因为题目数据结构中给了next指针,按照示例输出不难得出就是把完全二叉树从左到右“串”起来,最后一个节点指向NULL。

题目的Hint的给的提示深度优先搜索(我还没想到dfs的解法),但是这题用层序遍历(BFS)会比较简单,包括下一题LeetCode117—Populating Next Right Pointers in Each Node II 针对非完全二叉树的情形,也可以用相同的方法,事实上两者我用的同一份代码。

class Solution {
private:
void bfs(TreeLinkNode *root)//层序遍历
{
if (root == NULL)
return;
vector<TreeLinkNode*>temp;
vector<TreeLinkNode*>q;
int front = 0;
int rear = 1;
q.push_back(root);
while (front < q.size())
{
rear = q.size();
while (front < rear)
{
temp.push_back(q[front]);
if (q[front]->left != NULL)
q.push_back(q[front]->left);
if (q[front]->right != NULL)
q.push_back(q[front]->right);
++front;
}
int i;
for ( i = 0; i < temp.size()-1; i++)
{
temp[i]->next = temp[i + 1];
}
temp[i]->next = NULL;
temp.clear();//结束一层
}
}
public:
void connect(TreeLinkNode *root) {
bfs(root);
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: