Leetcode 树 Populating Next Right Pointers in Each Node II

本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie

Populating Next Right Pointers in Each Node II

Total Accepted: 9695 Total
Submissions: 32965

Follow up for problem "Populating Next Right Pointers in Each Node".

What if the given tree could be any binary tree? Would your previous solution still work?

Note:

  • You may only use constant extra space.

For example,

Given the following binary tree,

         1
/ \
2 3
/ \ \
4 5 7

After calling your function, the tree should look like:

         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL

题意:给定一棵随意二叉树(不一定是perfect binary tree),将它每个节点的next指针都指向该节点右边的节点

思路:bfs

这里不能用dfs了,仅仅能用bfs

bfs遍历将同一层的节点存放在同一个数组里,

然后在遍历每一个数组,将前面的节点和后面的节点connect起来,

最后一个节点和NULL connect起来

须要定义一个新的struct结构,保存指向每一个节点的指针和该节点所在的层

复杂度:时间O(n), 空间O( n)

相关题目:

Populating Next Right Pointers in Each Node

/**
* 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: struct TreeLinkNodeWithLevel
{
TreeLinkNode *p;
int level;
TreeLinkNodeWithLevel(TreeLinkNode *pp, int l):p(pp), level(l){}
}; void connect(TreeLinkNode *root) {
vector<vector<TreeLinkNode *> > nodes;
queue<TreeLinkNodeWithLevel> q;
q.push(TreeLinkNodeWithLevel(root, 0));
while (!q.empty())
{
TreeLinkNodeWithLevel cur = q.front(); q.pop();
if(!cur.p) continue;
if(cur.level >= nodes.size()){
vector<TreeLinkNode *> temp;
temp.push_back(cur.p);
nodes.push_back(temp);
}else{
nodes[cur.level].push_back(cur.p);
}
TreeLinkNodeWithLevel left(cur.p->left, cur.level + 1);
TreeLinkNodeWithLevel right(cur.p->right, cur.level + 1);
q.push(left);
q.push(right);
}
for(int i = 0; i < nodes.size(); i++){
for(int j = 0; j < nodes[i].size() - 1; j++){
nodes[i][j]->next = nodes[i][j + 1];
}
nodes[i][nodes[i].size() - 1]->next = NULL;
}
}
};
上一篇:【leetcode】Populating Next Right Pointers in Each Node II


下一篇:team foundation server——网络代码管理工具