[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 ...
 
随机推荐
- Linux的rwx
 - HDU1395 2^x mod n = 1——积与余数的性质
			
对于数论的学习比较的碎片化,所以开了一篇随笔来记录一下学习中遇到的一些坑,主要通过题目来讲解 本题围绕:积与余数 HDU1395 2^x mod n = 1 题目描述 输入一个数n,如果存在2的x次方 ...
 - Codeforces H. Malek Dance Club(找规律)
			
题目描述: Malek Dance Club time limit per test 1 second memory limit per test 256 megabytes input standa ...
 - Linux学习21-设置定时任务crontab
			
前言 做自动化测试写的脚本需设置定时任务,在指定的时间去执行,这就需要用到定时任务.之前用jenkins可以在里面设置定时任务,很好用,其实不用jenkins,在linux上也可以用crontab做个 ...
 - P1525 关押罪犯[扩展域并查集]
			
题目来源:洛谷 题目描述 S城现有两座监狱,一共关押着N名罪犯,编号分别为1−N.他们之间的关系自然也极不和谐.很多罪犯之间甚至积怨已久,如果客观条件具备则随时可能爆发冲突.我们用“怨气值”(一个正整 ...
 - node爬虫爬取中文时乱码问题 | nodejs gb2312、GBK中文乱码解决方法
			
iconv需要依赖native库,这样一来,在一些不支持native模块安装的虚拟主机和windows平台上,我们还是无法安心处理GBK编码. 老外写了一个通过纯Javascript转换编码的模块 i ...
 - hexo与github page搭建博客
			
安装 npm i hexo-cli -g hexo init blog cd blog npm install hexo server 发布hexo到github page npm i hexo-de ...
 - 域渗透:SPN(ServicePrincipal Names)的利用
			
SPN 简介:服务主体名称(SPN:ServicePrincipal Names)是服务实例(可以理解为一个服务,比如 HTTP.MSSQL)的唯一标识符.Kerberos 身份验证使用 SPN 将服 ...
 - LeetCode 1048. Longest String Chain
			
原题链接在这里:https://leetcode.com/problems/longest-string-chain/ 题目: Given a list of words, each word con ...
 - 关于System.MissingMethodException异常
			
什么是MissingMethodException 试图动态访问不存在的方法时引发的异常. 继承 Object Exception SystemException MemberAccessExcept ...