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 题目汇总

最新文章

  1. 一、Hello World
  2. TexturePacker大图还原成小图工具带源码
  3. Entity Framework 不支持DefaultValue
  4. html之ol标签
  5. [Android Exception 1A] -com.android.volley.NoConnectionError: java.io.InterruptedIOException
  6. svn merge部分的详细说明
  7. Intent.Action
  8. C语言的指针
  9. SQL Serverf 索引 - 索引压缩 、附加特性 &lt;第十篇&gt;
  10. go learning notes
  11. Android_65535问题的解决
  12. Pivot-Header的花式效果
  13. mysql的使用相关问题
  14. kali中的webshell工具--webacoo
  15. 使用Common.Logging+log4net规范日志管理【转载】
  16. 牛客网-2018年全国多校算法寒假训练营练习比赛(第四场)-A
  17. 基于 SOA 概念 RPC 框架 的 消息中心 云部署 设计 漫谈
  18. UVa140 Bandwidth 【最优性剪枝】
  19. Python2.7-os.path
  20. git和github的简单配合使用

热门文章

  1. Codeforces Round #598 (Div. 3)- E. Yet Another Division Into Teams - 动态规划
  2. drf框架总结复习(1)
  3. background-image:url为空引发的两次请求问题
  4. Topcoder10566 IncreasingNumber
  5. Centos7 yum安装postgresql 9.5
  6. tox 试用
  7. mapreduce数据处理——统计排序
  8. Java串口通信--------基于RXTX (附带资源地址)
  9. hbase 监控指标项
  10. pycharm无法识别自己的文件夹的程序