LeetCode_Populating Next Right Pointers in Each Node II
2024-09-20 19:28:49
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
}
};
最新文章
- 'hibernate.dialect' must be set when no Connection avalable’
- AjaxFileUpload 方法与原理分析
- [原创]pg_shard使用场景及功能测试
- psacct监视用户执行的命令,如cpu时间和内存战胜,实时进程记账
- JS高程5.引用类型(6)Array类型的位置方法,迭代方法,归并方法
- HDU 2045 不容易系列之(3)—— LELE的RPG难题(递归/动态规划)
- Google Firebase Unity接入的坑
- offsetof的意义
- [开发技巧]·HTML检测输入已完成自动填写下一个内容
- Virtual Box虚拟机Ubuntu系统安装及基本配置
- js中对于逗号的运算符!
- rails5 后台入门(api mode)
- 多线程Thread
- linux中运行.sql文件
- kvm企业级虚拟化环境部署
- 实战http切换成https
- (原)torch,caffe,python中读入数据的默认范围
- winform 批量控件取值赋值
- Python DDT(data driven tests)模块心得
- Windows Python 2.7环境搭建
热门文章
- Codeforces 538E Demiurges Play Again(博弈DP)
- Why Memory Barrier?
- Linux的capability深入分析(1)
- Mysql unix_timestamp() FROM_UNIXTIME和DATE_FORMAT(date,format)
- 【转】四步完成win7 ubuntu双系统安装(硬盘,无需光驱)
- 符号表(Symbol Tables)
- json对象与字符串的相互转换,数组和字符串的转换
- 短信猫编程的一些资料1(At指令发送短信)
- AngularJs练习Demo3
- 关于java WEB下载