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. 基于Docker容器使用NVIDIA-GPU训练神经网络

    一,nvidia K80驱动安装 1,  查看服务器上的Nvidia(英伟达)显卡信息,命令lspci |grep NVIDIA 05:00.0 3D controller: NVIDIA Corpo ...

  2. 初学Django基础02 ORM操作

    django的ORM操作 之前我们知道了models.py这个文件,这个文件是用来读取数据结构的文件,每次操作数据时都走这个模块 常用字段 AutoField int自增列,必须填入参数 primar ...

  3. DT资讯文章生成静态出现MySQL Error解决办法

    今天有个朋友的DT系统生成静态出现 MySQL Query:SELECT * FROM [pre]article_21 WHERE status=3 and itemid<>516548 ...

  4. siblings,next,prev

    同胞拥有相同的父元素. 通过 jQuery,您能够在 DOM 树中遍历元素的同胞元素. 在 DOM 树中水平遍历 siblings() next() nextAll() nextUntil() pre ...

  5. Codeforces1114F Please, another Queries on Array?

    题目链接:http://codeforces.com/problemset/problem/1114/F 题意:序列$a$,有两种操作,1 区间里的数同时乘上$x$ 2 求区间的积的欧拉函数 线段树好 ...

  6. 《三体》刘慈欣英文演讲:说好的星辰大海你却只给了我Facebook

    美国当地时间2018日11月8日,著名科幻作家刘慈欣被授予2018年度克拉克想象力贡献社会奖(Clarke Award for Imagination in Service to Society),表 ...

  7. redash oracle 数据源docker 镜像

    redash 官方的docker 镜像是没有包含oracle的,需要我们自己添加,参考了一个docker 镜像进行了简单的修改 Dockerfile FROM redash/redash:7.0.0. ...

  8. 函数(定义、参数、return、变量、作用域、预解析)

    一.函数定义 1.方式一       function 函数名(参数){  函数体  }——————函数声明的方法 function fn(a){ console.log(a); }: 2.方式二  ...

  9. Cobaltstrike与Metasploit会话转换

    这里只做记录,不做详解 0x00 实验环境 被控制机:192.168.126.129 Metasploit:192.168.126.128 Cobaltstrike:182...* 0x01 CS会话 ...

  10. hdu1501 Zipper[简单DP]

    目录 题目地址 题干 代码和解释 参考 题目地址 hdu1501 题干 代码和解释 最优子结构分析:设这三个字符串分别为a.b.c,如果a.b可以组成c,那么c的最后一个字母必定来自a或者b的最后一个 ...