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

116. Populating Next Right Pointers in Each Node的延续,如果给定的树是任何二叉树,不一定是完全二叉树,就是说不是每个节点都包含有两个子节点。

解法1:BFS, easy but not constant space, Complexity: time O(N) space O(N) - queue

解法2: Iteration - use dummy node to keep record of the next level's root to refer pre travel current level by referring to root in the level above,Complexity: time O(N) space O(1)

Java:BFS

class Solution {
public void connect(TreeLinkNode root) {
if(root == null)return;
Queue<TreeLinkNode> nodes = new LinkedList<>();
nodes.offer(root);
while(!nodes.isEmpty()){
int size = nodes.size();
for(int i = 0; i < size; i++){
TreeLinkNode cur = nodes.poll();
TreeLinkNode n = null;
if(i < size - 1){
n = nodes.peek();
}
cur.next = n;
if(cur.left != null)nodes.offer(cur.left);
if(cur.right != null)nodes.offer(cur.right);
} }
}
}

Java: Iteration

class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode dummy = new TreeLinkNode(0);
TreeLinkNode pre = dummy;//record next root
while(root != null){
if(root.left != null){
pre.next = root.left;
pre = pre.next;
}
if(root.right != null){
pre.next = root.right;
pre = pre.next;
}
root = root.next;//reach end, update new root & reset dummy
if(root == null){
root = dummy.next;
pre = dummy;
dummy.next = null;
}
}
}
} 

Java:

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;//currnet level's head
TreeLinkNode current = null;//current level's pointer while(lastHead!=null){
lastCurrent = lastHead; while(lastCurrent!=null){
//left child is not null
if(lastCurrent.left!=null) {
if(currentHead == null){
currentHead = lastCurrent.left;
current = lastCurrent.left;
}else{
current.next = lastCurrent.left;
current = current.next;
}
} //right child is not null
if(lastCurrent.right!=null){
if(currentHead == null){
currentHead = lastCurrent.right;
current = lastCurrent.right;
}else{
current.next = lastCurrent.right;
current = current.next;
}
} lastCurrent = lastCurrent.next;
} //update last head
lastHead = currentHead;
currentHead = null;
}
}

Python:

class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
self.next = None def __repr__(self):
if self is None:
return "Nil"
else:
return "{} -> {}".format(self.val, repr(self.next)) class Solution:
# @param root, a tree node
# @return nothing
def connect(self, root):
head = root
while head:
prev, cur, next_head = None, head, None
while cur:
if next_head is None:
if cur.left:
next_head = cur.left
elif cur.right:
next_head = cur.right if cur.left:
if prev:
prev.next = cur.left
prev = cur.left if cur.right:
if prev:
prev.next = cur.right
prev = cur.right cur = cur.next
head = next_head

C++:

class Solution {
public:
void connect(TreeLinkNode *root) {
TreeLinkNode *dummy = new TreeLinkNode(0), *t = dummy;
while (root) {
if (root->left) {
t->next = root->left;
t = t->next;
}
if (root->right) {
t->next = root->right;
t = t->next;
}
root = root->next;
if (!root) {
t = dummy;
root = dummy->next;
dummy->next = NULL;
}
}
}
};

  

类似题目:

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

All LeetCode Questions List 题目汇总

[LeetCode] 117. Populating Next Right Pointers in Each Node II 每个节点的右向指针 II的更多相关文章

  1. leetCode 116.Populating Next Right Pointers in Each Node (为节点填充右指针) 解题思路和方法

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

  2. Java for 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 tre ...

  3. leetcode 117 Populating Next Right Pointers in Each Node II ----- java

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

  4. 117 Populating Next Right Pointers in Each Node II 每个节点的右向指针 II

    这是“每个节点的右向指针”问题的进阶.如果给定的树可以是任何二叉树,该怎么办?你以前的解决方案仍然有效吗?注意:    你只能使用恒定的空间.例如,给定以下二叉树,         1       / ...

  5. Leetcode#117 Populating Next Right Pointers in Each Node II

    原题地址 二叉树的层次遍历. 对于每一层,依次把各节点连起来即可. 代码: void connect(TreeLinkNode *root) { if (!root) return; queue< ...

  6. 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 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...

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

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

  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@ [116/117] Populating Next Right Pointers in Each Node I & II (Tree, BFS)

    https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/ Follow up for problem ...

随机推荐

  1. 万众期待的kintone开发账号免费开放申请啦!

    亲爱的小伙伴们,等了很久很久的kintone开发账号终于可以免费申请使用了! 有人想问了,什么是kintone? kintone是指无需开发知识,即可根据公司业务轻松创建系统的Cybozu的云服务. ...

  2. 使用CEfSharp之旅(8)CEFSharp 使用代理 更换位置IP

    直接上代码: var settings = new CefSettings(); settings.CachePath = "cache"; settings.CefCommand ...

  3. [转]Linux-虚拟网络设备-tun/tap

    转: 原文:https://blog.csdn.net/sld880311/article/details/77854651 ------------------------------------- ...

  4. 关于AndroidStudio的apk打包遇到的问题记录

    12月份末尾,想来个总结,主要是得记一些重要的. 首先就得是AndroidStudi内的apk打包,就是弄当前项目app的安装包出来. 下面就说下具体步骤和注意问题. 首先 : 看到AndroidSt ...

  5. 关于原生js的节点兼容性

    关于节点的兼容性: 1:获取元素的子节点 a: childNodes:获取元素的子节点,空文本,非空文本,注释,获取的比较全面, 如果只是想获取元素的子节点,请用(children) b:     c ...

  6. 域权限维持:Ptk(Pass The Ticket)

    Kerberos协议传送门:https://www.cnblogs.com/zpchcbd/p/11707302.html 1.黄金票据 2.白银票据

  7. LeetCode 1239. Maximum Length of a Concatenated String with Unique Characters

    原题链接在这里:https://leetcode.com/problems/maximum-length-of-a-concatenated-string-with-unique-characters ...

  8. ASP.net MVC C# 当前上下文中不存在名称"viewbag"

    出现的错误如下: 错误 2 当前上下文中不存在名称“model” e:\Stuff\projects\蓝狐软件工作室\src\Lanhu.Admin\Views\Student\Index.cshtm ...

  9. 如何抓取微信小程序的源码?

    一.引言: 在工作中我们会想把别人的代码直接拿过来进行参考,当然这个更多的是前端代码的进行获取. 那么微信小程序的代码怎么样获取呢?  参考 https://blog.csdn.net/qq_4113 ...

  10. dinoql 试用

    dinoql 前面有过介绍,详细的参考文档即可,这篇主要是简单使用 注意目前dinoql 直接通过node 运行会有window 的问题,有好几种解决方法,后边会说明 环境准备 项目初始化 yarn ...