Question

Given a binary tree

    struct TreeLinkNode {
TreeLinkNode *left;
TreeLinkNode *right;
TreeLinkNode *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note:

  • You may only use constant extra space.
  • You may assume that it is a perfect binary tree (ie, all leaves are at the same level, and every parent has two children).

For example,
Given the following perfect binary tree,

         1
/ \
2 3
/ \ / \
4 5 6 7

After calling your function, the tree should look like:

         1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL

Solution 1 -- BFS

Key to the solution is to traverse tree level by level. Therefore, we can use BFS. Time complexity O(n), n is the number of nodes, and space cost is 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) {
// We can use BFS to solve this problem
List<TreeLinkNode> current = new ArrayList<TreeLinkNode>();
List<TreeLinkNode> next;
if (root == null)
return;
current.add(root);
while (current.size() > 0) {
next = new ArrayList<TreeLinkNode>();
int length = current.size();
for (int i = 0; i < length; i++) {
TreeLinkNode currentTreeNode = current.get(i);
if (i < length - 1)
currentTreeNode.next = current.get(i + 1);
else
currentTreeNode.next = null;
if (currentTreeNode.left != null)
next.add(currentTreeNode.left);
if (currentTreeNode.right != null)
next.add(currentTreeNode.right);
}
current = next;
}
}
}

Solution 2 -- Recursive

Consider for one node, the connection is done when:

1. Its left node (if exists) connect to its right node.

2. Its right node (if exists) connect to its next node's left child.

3. Its left child and right child are all connected.

Note the prerequisite for this problem is perfect binary tree (every parent has two children). Time complexity O(n), space cost O(1).

 /**
* 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;
if (root.left != null)
root.left.next = root.right;
if (root.right != null && root.next != null)
root.right.next = root.next.left;
connect(root.left);
connect(root.right);
}
}

Solution 3 -- Four Pointers

We can use four pointers to traverse the tree.

(referrence: ProgramCreek)

 /**
* 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 lastHead = root;//prevous level's head
TreeLinkNode lastCurrent = null;//previous level's pointer
TreeLinkNode currentHead = null;//current level's head
TreeLinkNode current = null;//current level's pointer while (lastHead != null) {
lastCurrent = lastHead;
currentHead = lastHead.left;
current = lastCurrent.left;
while (lastCurrent != null && current != null) {
current.next = lastCurrent.right;
current = current.next;
lastCurrent = lastCurrent.next;
if (lastCurrent != null) {
current.next = lastCurrent.left;
current = current.next;
}
}
lastHead = currentHead;
currentHead = null;
}
}
}

Populating Next Right Pointers in Each Node 解答的更多相关文章

  1. Populating Next Right Pointers in Each Node II 解答

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

  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 笔记 116 - Populating Next Right Pointers in Each Node

    题目链接:Populating Next Right Pointers in Each Node | LeetCode OJ Given a binary tree struct TreeLinkNo ...

  4. [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 ...

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

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

  6. LEETCODE —— Populating Next Right Pointers in Each Node

    Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode * ...

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

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

  8. 【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 ...

  9. 【leetcode】Populating Next Right Pointers in Each Node

    Populating Next Right Pointers in Each Node Given a binary tree struct TreeLinkNode { TreeLinkNode * ...

随机推荐

  1. 关于链表的一些重要操作(Important operations on a Linked List)

    上篇博文中讨论了链表的一些基本操作: 链表的基本操作(Basic Operations on a Linked List) 然而,为创建一个多功能的链表,在深度学习之前我们还需要了解更多的链表操作. ...

  2. Java 自定义实现 LRU 缓存算法

    背景 LinkedHashMap继承自HashMap,内部提供了一个removeEldestEntry方法,该方法正是实现LRU策略的关键所在,且HashMap内部专门为LinkedHashMap提供 ...

  3. mysql的日志

    是否启用了日志mysql>show variables like ‘log_bin’; 怎样知道当前的日志mysql> show master status; 看二进制日志文件用mysql ...

  4. SSH方式登录github出现Permission denied (publickey)

    今天在公司上传了代码,回到家pull,结果竟然出现了“Permission denied (publickey)“这种东西.第一反应是key不对,可是上次明明用key登录过,不可能不对啊,难道是文件被 ...

  5. java实现点名,并记录被点次数

    java实现点名,并记录被点次数 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStrea ...

  6. HDU 1248 寒冰王座(全然背包:入门题)

    HDU 1248 寒冰王座(全然背包:入门题) http://acm.hdu.edu.cn/showproblem.php?pid=1248 题意: 不死族的巫妖王发工资拉,死亡骑士拿到一张N元的钞票 ...

  7. Android应用程序发送广播(sendBroadcast)的过程分析

    文章转载至CSDN社区罗升阳的安卓之旅,原文地址:http://blog.csdn.net/luoshengyang/article/details/6744448 前面我们分析了Android应用程 ...

  8. Android-----------国际化多国语言文件夹命名汇总

    *如果不区分地区,则不加后面的-rxx内容 Arabic, Egypt (ar_rEG) —————————–阿拉伯语,埃及      Arabic, Israel (ar_rIL) ———————— ...

  9. T4模板_根据DB生成实体类

    为了减少重复劳动,可以通过T4读取数据库表结构,生成实体类,用下面的实例测试了一下 1.首先创建一个项目,并添加文本模板: 2.添加 文本模板: 3.向T4文本模板文件添加代码: <#@ tem ...

  10. spring cuowu

    spring常见错误总结 在学习spring过程中遇见了种种不同的异常错误,这里做了一下总结,希望遇见类似错误的同学们共勉一下. 1. 错误一 Error creating bean with nam ...