题目描述:
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
Hide Tags Tree Depth-first Search
分析:此题的思路和Populating Next Right Pointers in Each Node(http://blog.csdn.net/bu_min/article/details/45921295)是一样的,只是处理的时候,要跳过二叉树的空节点。next指针要指向其右边第一个非空节点。
只需在上一题的基础上跳过二叉树中的空节点,处理每一层的时候,注意判断其左右孩子是否为空,只将非空节点放入向量和队列中。
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
Hide Tags Tree Depth-first Search
分析:此题的思路和Populating Next Right Pointers in Each Node(http://blog.csdn.net/bu_min/article/details/45921295)是一样的,只是处理的时候,要跳过二叉树的空节点。next指针要指向其右边第一个非空节点。
只需在上一题的基础上跳过二叉树中的空节点,处理每一层的时候,注意判断其左右孩子是否为空,只将非空节点放入向量和队列中。
以下是C++实现代码:
/*/44ms*/
/**
* 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) {
if(root == NULL)
return;
TreeLinkNode *cur = root;
queue<TreeLinkNode* > q;
root->next = NULL; //修改root的next指针
if(cur != NULL)
{
q.push(cur);
while(!q.empty()) //此处判断是否最后一层处理完
{
int len = 0;
vector<TreeLinkNode*> vec; //存放即将要处理得层的每个节点的左右节点
while(!q.empty()) //此处判断某一层是否处理完
{
TreeLinkNode *cur = q.front();
q.pop();
if(cur->left != NULL) //依次将非空的左右孩子放入vec中
{
vec.push_back(cur->left);
len++;
}
if(cur->right != NULL)
{
vec.push_back(cur->right);
len++;
}
}
if(len > 0) 当有非空左右孩子时,才修改next指针,将其指向右边的第一个非空节点
{
for(int i = 0; i < len-1; i++)
{
q.push(vec[i]);
vec[i]->next = vec[i+1];
}
q.push(vec[len-1]);
vec[len - 1]->next = NULL;
}
}
}
return;
}
};