LeetCode - Populating Next Right Pointers in Each Node II
2024-08-29 08:42:35
题目:
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的左右进行连接操作,然后先递归右树,再递归左树。
package tree; public class PopulatingNextRightPointersInEachNodeII { public void connect(TreeLinkNode root) {
if (root == null || (root.left == null && root.right == null)) return; TreeLinkNode next = root.next;
while (next != null) {
if(next.left != null) {
next = next.left;
break;
} if (next.right != null) {
next = next.right;
break;
} next = next.next;
} if (root.right != null)
root.right.next = next; if (root.left != null)
root.left.next = root.right == null ? next : root.right; connect(root.right);
connect(root.left);
} }
最新文章
- git 命令大全
- 20145208实验一 Java开发环境的熟悉
- 【InstallShield】 为什么卸载后有的文件没有删掉
- 一篇文章让你读懂 OpenStack 的起源、架构和应用
- 用Processon在线绘制UML的尝试
- Truck History--poj1789
- UESTC_最少花费 2015 UESTC Training for Dynamic Programming<;Problem D>;
- SQLServer类型与Java类型转换问题解决
- centos 6.6 ios镜像文件 下载 官网和阿里云两种方式教你下载
- 我的第一个python web开发框架(3)——怎么开始?
- CSS中的选择器之类选择器和id选择器
- Unity使用脚本进行批量动态加载贴图
- day13笔记
- 好程序员分享Javascript设计模式
- oa项目环境搭建的操作步骤详解
- SSH框架学习摸索记
- 6.18_web服务器内容
- 【入门推荐】SQL注入进行WebShell渗透测试的基础概览
- CommonCode升级:把不常用的Sqlite独立出去
- WPF实现的简单饼图
热门文章
- 算法:x的n次方
- java算法(一)
- js模版引擎handlebars.js实用教程——由于if功力不足引出的Helper
- 《OOC》笔记(4)——自动化地将C#代码转化为C代码(结构版)
- Windows Live Writer 初次使用
- 为 WSUS 服务器定期运行清理向导
- ssl小结
- 第十六回 IoC组件Unity续~批量动态为Unity添加类型和行为
- Atitit.java图片图像处理attilax总结&#160;&#160;BufferedImage&#160;extends&#160;java.awt.Image获取图像像素点image.getRGB(i,&#160;lineIndex);&#160;图片剪辑/AtiPlatf_cms/src/com/attilax/img/imgx.javacutImage图片处理titit 判断判断一张图片是否包含另一张小图片&#160;atitit 图片去噪算法的原理与
- spring容器对bean生命周期的管理三中方式