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

117. Populating Next Right Pointers in Each Node II

2018-03-15 10:20 253 查看
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

使用递归的解法,先循环查找root右边第一个同层节点p,则root->left的next若root->right存在则为root->right,不存在则为p,root->right的next为p,然后递归解出子树。
这里特别注意,最后递归调用时,需要先连接右子树,再连接左子树。如果先连接左子树,此时root右边p->next还未完全建立,可能无法找到同层的第一个节点,导致后续连接错误。class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==nullptr) return;
TreeLinkNode *p=root->next;
while(p)
{
if(p->left)
{
p=p->left;
break;
}
if(p->right)
{
p=p->right;
break;
}
p=p->next;
}
if(root->left)
root->left->next=root->right?root->right:p;
if (root->right) root->right->next = p;
connect(root->right);//注意先递归右子树,再递归左子树
connect(root->left);
}
};

非递归有两种做法,第一种用一个队列实现,队列中依次存储每一层的节点,用length指定当前层剩余节点,每当当前层节点更新完毕,则将队列的长度重新赋给length,又开始循环。class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==nullptr) return;
queue<TreeLinkNode *> q;
q.push(root);
while(!q.empty())
{
int length=q.size();
for(int i=0;i<length;i++)
{
TreeLinkNode * p=q.front();
q.pop();
if(i<length-1)//若将判断写为if(!q.empty()),则会产生错误,因为此时q的长度在不断更新
p->next=q.front();
if(p->left)
q.push(p->left);
if(p->right)
q.push(p->right);
}
}
}
};O(1)的非递归解法:
主要用到一个dummy节点指向下一层第一个节点,然后用pre一个一个遍历,若到本层最后一个节点,则将root指向dummy->next,即下一层的第一个节点,dummy置为NULL,pre重新指向dummy。
1 -> NULL
(pre) / \
dummy->2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
class Solution {
public:
void connect(TreeLinkNode *root) {
if(root==nullptr) return;
TreeLinkNode * dummy=new TreeLinkNode(-1),* pre=dummy;
while(root)
{
if(root->left)
{
pre->next=root->left;
pre=pre->next;
}
if(root->right)
{
pre->next=root->right;
pre=pre->next;
}
root=root->next;
if(!root)
{
root=dummy->next;
dummy->next=NULL;
pre=dummy;
}
}
}
};
参考:http://www.cnblogs.com/grandyang/p/4290148.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: