题目:

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);
} }

最新文章

  1. git 命令大全
  2. 20145208实验一 Java开发环境的熟悉
  3. 【InstallShield】 为什么卸载后有的文件没有删掉
  4. 一篇文章让你读懂 OpenStack 的起源、架构和应用
  5. 用Processon在线绘制UML的尝试
  6. Truck History--poj1789
  7. UESTC_最少花费 2015 UESTC Training for Dynamic Programming<Problem D>
  8. SQLServer类型与Java类型转换问题解决
  9. centos 6.6 ios镜像文件 下载 官网和阿里云两种方式教你下载
  10. 我的第一个python web开发框架(3)——怎么开始?
  11. CSS中的选择器之类选择器和id选择器
  12. Unity使用脚本进行批量动态加载贴图
  13. day13笔记
  14. 好程序员分享Javascript设计模式
  15. oa项目环境搭建的操作步骤详解
  16. SSH框架学习摸索记
  17. 6.18_web服务器内容
  18. 【入门推荐】SQL注入进行WebShell渗透测试的基础概览
  19. CommonCode升级:把不常用的Sqlite独立出去
  20. WPF实现的简单饼图

热门文章

  1. 算法:x的n次方
  2. java算法(一)
  3. js模版引擎handlebars.js实用教程——由于if功力不足引出的Helper
  4. 《OOC》笔记(4)——自动化地将C#代码转化为C代码(结构版)
  5. Windows Live Writer 初次使用
  6. 为 WSUS 服务器定期运行清理向导
  7. ssl小结
  8. 第十六回 IoC组件Unity续~批量动态为Unity添加类型和行为
  9. Atitit.java图片图像处理attilax总结  BufferedImage extends java.awt.Image获取图像像素点image.getRGB(i, lineIndex); 图片剪辑/AtiPlatf_cms/src/com/attilax/img/imgx.javacutImage图片处理titit 判断判断一张图片是否包含另一张小图片 atitit 图片去噪算法的原理与
  10. spring容器对bean生命周期的管理三中方式