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

  

/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
while(root){
TreeLinkNode *head = NULL;
TreeLinkNode *pre = NULL;
for(;root;root = root->next){
if(!head) head = root->left ? root->left : root->right; if(root->left){
if(pre)pre->next = root->left;
pre = root->left;
} if(root->right){
if(pre) pre->next = root->right;
pre = root->right;
}
}// end of for
root = head;
} // end of while
}
};

最新文章

  1. 'hibernate.dialect' must be set when no Connection avalable’
  2. AjaxFileUpload 方法与原理分析
  3. [原创]pg_shard使用场景及功能测试
  4. psacct监视用户执行的命令,如cpu时间和内存战胜,实时进程记账
  5. JS高程5.引用类型(6)Array类型的位置方法,迭代方法,归并方法
  6. HDU 2045 不容易系列之(3)—— LELE的RPG难题(递归/动态规划)
  7. Google Firebase Unity接入的坑
  8. offsetof的意义
  9. [开发技巧]·HTML检测输入已完成自动填写下一个内容
  10. Virtual Box虚拟机Ubuntu系统安装及基本配置
  11. js中对于逗号的运算符!
  12. rails5 后台入门(api mode)
  13. 多线程Thread
  14. linux中运行.sql文件
  15. kvm企业级虚拟化环境部署
  16. 实战http切换成https
  17. (原)torch,caffe,python中读入数据的默认范围
  18. winform 批量控件取值赋值
  19. Python DDT(data driven tests)模块心得
  20. Windows Python 2.7环境搭建

热门文章

  1. Codeforces 538E Demiurges Play Again(博弈DP)
  2. Why Memory Barrier?
  3. Linux的capability深入分析(1)
  4. Mysql unix_timestamp() FROM_UNIXTIME和DATE_FORMAT(date,format)
  5. 【转】四步完成win7 ubuntu双系统安装(硬盘,无需光驱)
  6. 符号表(Symbol Tables)
  7. json对象与字符串的相互转换,数组和字符串的转换
  8. 短信猫编程的一些资料1(At指令发送短信)
  9. AngularJs练习Demo3
  10. 关于java WEB下载