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

最开始的想法是用一个队列和一个列表。当前遍历的层的元素放在队列中,在遍历当前层的时候,把下一层元素的next指针设置好,并且把下一层的元素放在列表中。之所以要用列表,是因为当遍历一个node的孩子的时候,它在next指针下的前驱就是列表中的最后一个元素,如果用队列的话就取不出最后一个元素,所以这里要用列表。在一层遍历结束后,要把列表中的元素全部放入到队列中,开始下一层的遍历,代码如下:

 /**
* 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; Queue<TreeLinkNode> currLevel = new LinkedList<TreeLinkNode>();
List<TreeLinkNode> nextLevel = new ArrayList<TreeLinkNode>(); currLevel.add(root); while(!currLevel.isEmpty()){
while(!currLevel.isEmpty()){
TreeLinkNode temp = currLevel.poll();
if(temp.left != null){
if(!nextLevel.isEmpty() && nextLevel.get(nextLevel.size()-1).next == null)
nextLevel.get(nextLevel.size()-1).next = temp.left;
nextLevel.add(temp.left);
}
if(temp.right != null){
if(!nextLevel.isEmpty() && nextLevel.get(nextLevel.size()-1).next == null)
nextLevel.get(nextLevel.size()-1).next = temp.right;
nextLevel.add(temp.right);
}
}
List<TreeLinkNode> passby = new ArrayList<TreeLinkNode>(nextLevel);
currLevel.addAll(passby);
nextLevel.clear();
}
}
}

但是题目中要求要常数的额外空间,上述代码居然也AC了,可见leetcode要求不是特别严格。

那么我们怎么把上述代码修改成原地算法呢?

首先,对于上述用到的列表,其实我们每次只需要列表的最后一个元素,它是当前遍历节点的孩子的前驱。如题目中所示的例子,在遍历2的右子5的时候,只要知道它的前驱是4,即刚刚遍历过的2的左子即可;同理,在遍历节点3的时候,要知道它的右孩子的前驱,只要知道刚刚遍历到的下一层节点5就可以了;所以我们只需要一个TreeNode prev记录刚刚通过父节点遍历到的下一层的节点就可以了。

其次,对于上述用到的队列,队列中元素的先后顺序其实我们在遍历上一层的时候确定这一层元素的next指针,那么在遍历这一层的时候就可以利用这个next指针了,但是仍然需要知道这一层的起点指针,这个起点指针也可以在遍历上一层的时候确定。

修改后的代码如下:

 /**
* 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) {
TreeLinkNode first = root;
while(first != null){
TreeLinkNode pointer = first;
first = null;
TreeLinkNode prev = null; while(pointer != null){
//更新first
if(pointer.left != null){
if(first == null){
first = pointer.left;
prev = first;
}else{
prev.next = pointer.left;
prev = prev.next;
}
} if(pointer.right != null){
if(first == null){
first = pointer.right;
prev = first;
}else{
prev.next = pointer.right;
prev = prev.next;
}
} pointer = pointer.next;
}
}
}
}

【leetcode刷题笔记】Populating Next Right Pointers in Each Node II的更多相关文章

  1. LeetCode(117) Populating Next Right Pointers in Each Node II

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

  2. 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 ...

  3. leetcode 199. Binary Tree Right Side View 、leetcode 116. Populating Next Right Pointers in Each Node 、117. Populating Next Right Pointers in Each Node II

    leetcode 199. Binary Tree Right Side View 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...

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

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

  5. LeetCode: Populating Next Right Pointers in Each Node II 解题报告

    Populating Next Right Pointers in Each Node IIFollow up for problem "Populating Next Right Poin ...

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

    Populating Next Right Pointers in Each Node II 题解 原创文章,拒绝转载 题目来源:https://leetcode.com/problems/popul ...

  7. 【leetcode】Populating Next Right Pointers in Each Node II

    Populating Next Right Pointers in Each Node II Follow up for problem "Populating Next Right Poi ...

  8. Leetcode 树 Populating Next Right Pointers in Each Node II

    本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie Populating Next Right Pointers in Each Node II ...

  9. 【LeetCode】117. Populating Next Right Pointers in Each Node II (2 solutions)

    Populating Next Right Pointers in Each Node II Follow up for problem "Populating Next Right Poi ...

  10. 29. Populating Next Right Pointers in Each Node && Populating Next Right Pointers in Each Node II

    Populating Next Right Pointers in Each Node OJ: https://oj.leetcode.com/problems/populating-next-rig ...

随机推荐

  1. 算不算类似微信小程序

    这几天微信发布的微信里生成小程序,刷爆了朋友圈. 微信生成的小程序不用下载安装就能在手机里出现,即用即删. 想到这里,我想到苹果手机本身再带类似于微信的小程序的呈现方式,也可以即用即删,那是我在去年久 ...

  2. 【React Native开发】React Native配置执行官方样例-刚開始学习的人的福音(8)

    ),React Native技术交流4群(458982758),请不要反复加群! 欢迎各位大牛,React Native技术爱好者加入交流!同一时候博客左側欢迎微信扫描关注订阅号,移动技术干货,精彩文 ...

  3. TP框架的修改,删除

    先把数据库的素具显示出来 public function xiugai() { $code= "n001";//修改的主键值 $n = M("nation"); ...

  4. K-Piggy-Bank

    Piggy-Bank Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)Total ...

  5. Entity Framework 4.1 : 贪婪加载和延迟加载

    这篇文章将讨论查询结果的加载控制. EF4.1 允许控制对象之间的关系,当我们进行查询的时候,哪些关系的数据将会被加载到内存呢?所有相关的对象都需要吗?在一些场合可能有意义,例如,当查询的实体仅仅拥有 ...

  6. Linux开启防火墙后,设置允许通过的端口

    安装Firewall命令: yum install firewalld firewalld-config Firewall开启端口命令: firewall-cmd --zone=public --ad ...

  7. Python——Numpy的random子库

    NumPy的random子库 np.random.* np.random.rand() np.random.randn() np.random.randint() import numpy as np ...

  8. Tensorflow官方文档中文版——第一章

    第一示例: import tensorflow as tf import numpy as np x_data=np.float32(np.random.rand(,))#随机输入 y_data=np ...

  9. mybatis_1

    mybatis-config.xml <?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE co ...

  10. centos7下Zookeeper+sheepdog集群搭建

    zookeeper 安装命令 yum install zookeeper -y            (版本:zookeeper.x86_64      3.4.6-1) yum install zo ...