Populating Next Right Pointers in Each Node II

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
 
与I的思路类似
left->next=father->right
right->next=father->next->left;
 

只是当我们没有找到时,father=father->next;

需要注意,先搜索右子树,再搜索左子树
 
 
 /**
* 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;
} if(root->left!=NULL)
{
if(root->right!=NULL)
{
root->left->next=root->right;
}
else
{
TreeLinkNode *tmp=root->next;
root->left->next=NULL;
while(tmp!=NULL)
{
if(tmp->left!=NULL)
{
root->left->next=tmp->left;
break;
} if(tmp->right!=NULL)
{
root->left->next=tmp->right;
break;
}
tmp=tmp->next;
}
}
} if(root->right!=NULL)
{
TreeLinkNode *tmp=root->next;
root->right->next=NULL;
while(tmp!=NULL)
{
if(tmp->left!=NULL)
{
root->right->next=tmp->left;
break;
} if(tmp->right!=NULL)
{
root->right->next=tmp->right;
break;
}
tmp=tmp->next;
}
} connect(root->right);
connect(root->left); }
};

最新文章

  1. Jingle 相关问题
  2. chmod 和 chown 的用法
  3. 山东理工大学第七届ACM校赛-飞花的鱼塘 分类: 比赛 2015-06-26 10:30 43人阅读 评论(0) 收藏
  4. 使用ViewPager+Fragment来实现带滚动条的多屏滑动-IndicatorFragmentActivity
  5. 关于python抓取google搜索结果的若干问题
  6. MySQL学习笔记之中的一个 MySQL入门
  7. .NET面试题目二
  8. 关于js中window.location.href,location.href,parent.location.href,top.location.href用法
  9. javascript . 05 json的组成、for...in 遍历对象、简单数据类型与复杂数据类型的传值与传址、内置对象
  10. php session 和cookie
  11. mysql中的视图、事务和索引
  12. sql的having深入理解;group by只返回一组的一行,compute更好
  13. javascript内置对象速查(一)
  14. python自定义pi函数的代码
  15. KNN算法基本实例
  16. 伪静态与重定向--RewriteBase
  17. Spring+CXF整合来管理webservice(服务器启动发布webservice)
  18. idea中maven中jdk版本的选择(转)
  19. Indy Changed from Indy10
  20. 什么是 CLR(转)

热门文章

  1. jsp简单标签开发(一)
  2. linux标准输入输出及错误输出
  3. Linq_Lambda GroupBy使用笔记
  4. 15分钟学会使用Git和远程代码库
  5. javascript的对象 和 JSON 对象?
  6. 关于学习session的一二
  7. Redis优化之CPU充分利用
  8. oracle 行列转换的运用
  9. 使用IzPack打包JAVA Web应用程序
  10. HNU 12888 Encryption(map容器)