[LeetCode] 117. Populating Next Right Pointers in Each Node II 每个节点的右向指针 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
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的更多相关文章
- leetCode 116.Populating Next Right Pointers in Each Node (为节点填充右指针) 解题思路和方法
Given a binary tree struct TreeLinkNode { TreeLinkNode *left; TreeLinkNode *right; TreeLinkNode *nex ...
- 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 ...
- 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 ...
- 117 Populating Next Right Pointers in Each Node II 每个节点的右向指针 II
这是“每个节点的右向指针”问题的进阶.如果给定的树可以是任何二叉树,该怎么办?你以前的解决方案仍然有效吗?注意: 你只能使用恒定的空间.例如,给定以下二叉树, 1 / ...
- Leetcode#117 Populating Next Right Pointers in Each Node II
原题地址 二叉树的层次遍历. 对于每一层,依次把各节点连起来即可. 代码: void connect(TreeLinkNode *root) { if (!root) return; queue< ...
- 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 这个题实际上就是把每一行最右侧的树打印出来,所以实际上还是一个层次遍历. 依旧利用之前层次遍历的代码,每次大的循环存 ...
- 【LeetCode】117. Populating Next Right Pointers in Each Node II 解题报告(Python)
[LeetCode]117. Populating Next Right Pointers in Each Node II 解题报告(Python) 标签: LeetCode 题目地址:https:/ ...
- 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 ...
- 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 ...
随机推荐
- ThreadLocal源码原理以及防止内存泄露
ThreadLocal的原理图: 在线程任务Runnable中,使用一个及其以上ThreadLocal对象保存多个线程的一个及其以上私有值,即一个ThreadLocal对象可以保存多个线程一个私有值. ...
- 小程序~列表渲染~key
如果列表中项目的位置会动态改变或者有新的项目添加到列表中,并且希望列表中的项目保持自己的特征和状态(如 <input/> 中的输入内容, <switch/> 的选中状态),需要 ...
- app安全测试初级
分析方法:静态分析 主要是利用apktool.dex2jar.jd-gui.smali2dex等静态分析工具对应用进行反编译,并对反编译后的java文件.xml文件等文件进行静态扫描分析,通过关键词搜 ...
- Alpha冲刺(7/10)——2019.4.30
所属课程 软件工程1916|W(福州大学) 作业要求 Alpha冲刺(7/10)--2019.4.30 团队名称 待就业六人组 1.团队信息 团队名称:待就业六人组 团队描述:同舟共济扬帆起,乘风破浪 ...
- C++定义和初始化数组以及memset的使用(转)
一.一维数组 静态 int array[100]; 定义了数组array,并未对数组进行初始化 静态 int array[100] = {1,2}: 定义并初始化了数组array 动态 int* ar ...
- reshape()函数
""" 1.当原始数组A[4,6]为二维数组,代表4行6列. A.reshape(-1,8):表示将数组转换成8列的数组,具体多少行我们不知道,所以参数设为-1.用我们的 ...
- LeetCode 1059. All Paths from Source Lead to Destination
原题链接在这里:https://leetcode.com/problems/all-paths-from-source-lead-to-destination/ 题目: Given the edges ...
- oracle 按每天,每周,每月,每季度,每年查询统计数据
oracle 按每天,每周,每月,每季度,每年查询统计数据 //按天统计 select count(dataid) as 每天操作数量, sum() from tablename group by t ...
- learning svn diff --summarize
# svn diff --summarizeA armbian-custom-dc/test/4g-power.shA armbian-custom-dc/test/4g-reset.shM armb ...
- circus && web comsole docker-compose 独立部署web console 的一个bug
如果直接使用以下的docker-compose 文件部署会有通过多播通信获取endpoint 异常的问题(circus 在stats endpoint 获取少了一个c) 这个问题是部分网络情况下会出现 ...