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

SOLUTION 1

本题还是可以用Level Traversal 轻松解出,连代码都可以跟上一个题目一模一样。Populating Next Right Pointers in Each Node Total

但是不符合空间复杂度的要求:constant extra space.

时间复杂度: O(N)

 /**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode dummy = new TreeLinkNode(0);
Queue<TreeLinkNode> q = new LinkedList<TreeLinkNode>(); q.offer(root);
q.offer(dummy); while(!q.isEmpty()) {
TreeLinkNode cur = q.poll();
if (cur == dummy) {
if (!q.isEmpty()) {
q.offer(dummy);
}
continue;
} if (q.peek() == dummy) {
cur.next = null;
} else {
cur.next = q.peek();
} if (cur.left != null) {
q.offer(cur.left);
} if (cur.right != null) {
q.offer(cur.right);
}
} }
}

SOLUTION 2

我们可以用递归解出。注意从右往左加next。否则的话 右边未建立,左边你没找不到next. Space Complexity:

时间复杂度: O(N)

 public void connect(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode cur = root.next;
TreeLinkNode next = null;
// this is very important. should exit after found the next.
while (cur != null && next == null) {
if (cur.left != null) {
next = cur.left;
} else if (cur.right != null) {
next = cur.right;
} else {
cur = cur.next;
}
} if (root.right != null) {
root.right.next = next;
next = root.right;
} if (root.left != null) {
root.left.next = next;
} // The order is very important. We should deal with right first!
connect(root.right);
connect(root.left);
}

2014.1229 redo:

但现在leetcode加强数据了,不管怎么优化,递归的版本再也不能通过,都TLE

 // SOLUTION 2: REC
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode dummy = new TreeLinkNode(0);
TreeLinkNode pre = dummy; if (root.left != null) {
pre.next = root.left;
pre = root.left;
} if (root.right != null) {
pre.right = root.right;
pre = root.right;
} if (root.left == null && root.right == null) {
return;
} // Try to find the next node;
TreeLinkNode cur = root.next;
TreeLinkNode next = null;
while (cur != null) {
if (cur.left != null) {
next = cur.left;
break;
} else if (cur.right != null) {
next = cur.right;
break;
} else {
cur = cur.next;
}
} pre.next = next; if (root.right != null && (root.right.left != null || root.right.right != null)) {
connect(root.right);
} if (root.left != null && (root.left.left != null || root.left.right != null)) {
connect(root.left);
} }

SOLUTION 3

我们可以用Iterator 直接解出。并且不开辟额外的空间,也就是说空间复杂度是 O(1)

时间复杂度: O(N)

感谢 http://www.geeksforgeeks.org/connect-nodes-at-same-level-with-o1-extra-space/ 的作者

 /*
Solution 3: iterator with O(1) space.
*/
public void connect(TreeLinkNode root) {
if (root == null) {
return;
} connIterator(root);
} /*
This is a iterator version.
*/
public void connIterator(TreeLinkNode root) {
TreeLinkNode leftEnd = root;
while (leftEnd != null) {
TreeLinkNode p = leftEnd; // Connect all the nodes in the next level together.
while (p != null) { // find the
TreeLinkNode next = findLeftEnd(p.next); if (p.right != null) {
p.right.next = next;
next = p.right;
} if (p.left != null) {
p.left.next = next;
} // continue to deal with the next point.
p = p.next;
} // Find the left end of the NEXT LEVEL.
leftEnd = findLeftEnd(leftEnd);
} } // Find out the left end of the next level of Root TreeNode.
public TreeLinkNode findLeftEnd(TreeLinkNode root) {
while (root != null) {
if (root.left != null) {
return root.left;
} if (root.right != null) {
return root.right;
} root = root.next;
} return null;
}

SOLUTION 4 (2014.1229):

在sol3基础上改进,引入dummynode,我们就不需要先找到最左边的点了。空间复杂度是 O(1)时间复杂度: O(N)

 // SOLUTION 1: Iteration
public void connect1(TreeLinkNode root) {
if (root == null) {
return;
} TreeLinkNode leftEnd = root; // Bug 1: don't need " && leftEnd.left != null"
while (leftEnd != null) {
TreeLinkNode cur = leftEnd; TreeLinkNode dummy = new TreeLinkNode(0);
TreeLinkNode pre = dummy;
while (cur != null) {
if (cur.left != null) {
pre.next = cur.left;
pre = cur.left;
} if (cur.right != null) {
pre.next = cur.right;
pre = cur.right;
} cur = cur.next;
}
leftEnd = dummy.next;
}
}

CODE ON GITHUB:

https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/Connect2_2014_1229.java

Connect2.java

LeetCode: Populating Next Right Pointers in Each Node II 解题报告的更多相关文章

  1. 【LeetCode】117. Populating Next Right Pointers in Each Node II 解题报告(Python)

    [LeetCode]117. Populating Next Right Pointers in Each Node II 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...

  2. [LeetCode] Populating Next Right Pointers in Each Node II 每个节点的右向指针之二

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  3. LeetCode——Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  4. [leetcode]Populating Next Right Pointers in Each Node II @ Python

    原题地址:https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ 题意: Follow up ...

  5. LeetCode - Populating Next Right Pointers in Each Node II

    题目: Follow up for problem "Populating Next Right Pointers in Each Node". What if the given ...

  6. [LeetCode] [LeetCode] Populating Next Right Pointers in Each Node II

    Follow up for problem "Populating Next Right Pointers in Each Node". What if the given tre ...

  7. LeetCode:Populating Next Right Pointers in Each Node I II

    LeetCode:Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeL ...

  8. Leetcode 笔记 117 - Populating Next Right Pointers in Each Node II

    题目链接:Populating Next Right Pointers in Each Node II | LeetCode OJ Follow up for problem "Popula ...

  9. [LeetCode] Populating Next Right Pointers in Each Node 每个节点的右向指针

    Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *nex ...

随机推荐

  1. 〖Windows〗zigbee实验之cygwin编译tinyos.jar编译出错的解决方法

    1. 使用的cygwin安装包下载地址:cygwin-files.zip 2. 使用的一些rpm安装包的下载地址:cygwin_cc2430_rpms.zip 3. cygwin的默认安装目录是:C: ...

  2. 【FAI】七日年化收益与万份收益的理解

    七日年化收益:其实指的一年的收益(应该忽略”七日”),这里的七日指的是取最近七日年化的结果 万份收益:每万元每天的收益 可以使用下图来清晰识别: 例子: 10000元按照5%的七日年化收益计算的话: ...

  3. nginx1.9+新增tcp/udp代理stream

    [root@rhel nginx-]# ./configure --help --help print this message --prefix=PATH set installation pref ...

  4. iOS开发之复制字符串到剪贴板

    概述 一般有邀请复制链接需求功能,把字符串复制到系统剪贴板,供用户粘贴使用链接. 详细 代码下载:http://www.demodashi.com/demo/10714.html 一.主要思路 1.在 ...

  5. Android仿掌上英雄联盟首页,实现折叠效果

    概述 仿掌上英雄联盟首页的demo 详细 代码下载:http://www.demodashi.com/demo/10695.html 首页大概分为几个部分 状态栏 标题栏 轮播图 切换的Tab 资讯列 ...

  6. Spark GraphX 的数据可视化

    概述 Spark GraphX 本身并不提供可视化的支持, 我们通过第三方库 GraphStream 和 Breeze 来实现这一目标 详细 代码下载:http://www.demodashi.com ...

  7. Persona——Web人物角色介绍

    一.什么是人物角色? 人物角色,即persona([pə:’səunə]),这里讨论的主要是web persona,是指针对网站目标群体真实特征的勾勒,是真实用户的综合原型.我们对产品使用者的目标.行 ...

  8. VC6.0 +WDK 开发驱动的环境配置

    前段时间,系统偶感风寒,挂掉了,苦于又没有备份过,只有重装了.原来开发驱动的环境是VC6+DDK+DriverStudio3.2,当时配置的时候就花了好一阵功夫,也没有彻底搞清楚.现在要重装了,决定改 ...

  9. leetcode185 Department Top Three Salaries

    Employee表存储员工姓名.员工所在公寓.员工工资 Department表存储公寓id 评选出各个公寓的工资前三名的员工. 遇到的问题如下: limit,in等语句不能用在嵌套select语句中, ...

  10. AsyncTask与ProgressDialog使用笔记(安卓在背景运行耗时任务)

    AsyncTask用在需要在ui线程中调用.在背景线程中执行耗时任务.并且在ui线程中返回结果的场合.下面就是一个在背景中运行的AsyncTask的实现DownloadDBTask, Android中 ...