Populating Next Right Pointers in Each Node II
2017-04-07 22:08
281 查看
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,
After calling your function, the tree should look like:
Java代码:
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode cur=root;
TreeLinkNode head=root;
TreeLinkNode pre=null;
while(head!=null){
cur=head;
head=null;
pre=null;
while(cur!=null){
if(cur.left!=null){
if(pre!=null)pre.next=cur.left;
else head=cur.left;
pre=cur.left;
}
if(cur.right!=null){
if(pre!=null)pre.next=cur.right;
else head=cur.right;
pre=cur.right;
}
cur=cur.next;
}
}
}
时间复杂度O(N)
空间复杂度O(1)
思路:
在上一次已经连接好的情况下,再进行下一层的连接。
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
Java代码:
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode cur=root;
TreeLinkNode head=root;
TreeLinkNode pre=null;
while(head!=null){
cur=head;
head=null;
pre=null;
while(cur!=null){
if(cur.left!=null){
if(pre!=null)pre.next=cur.left;
else head=cur.left;
pre=cur.left;
}
if(cur.right!=null){
if(pre!=null)pre.next=cur.right;
else head=cur.right;
pre=cur.right;
}
cur=cur.next;
}
}
}
时间复杂度O(N)
空间复杂度O(1)
思路:
在上一次已经连接好的情况下,再进行下一层的连接。
相关文章推荐
- Populating Next Right Pointers in Each Node II
- leetcode Populating Next Right Pointers in Each Node II
- 【ATT】Populating Next Right Pointers in Each Node II
- 【Populating Next Right Pointers in Each Node II】cpp
- Populating Next Right Pointers in Each Node II
- (M)DFS:117. Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node (I & II)
- [leetcode][tree] Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II - LeetCode 117
- *LeetCode-Populating Next Right Pointers in Each Node II
- [leetcode]Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II leetcode java
- [LeetCode 117] Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node I, II
- [LeetCode] Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II 任意(非完美)二叉树添加next指针 @LeetCode
- LeetCode: Populating Next Right Pointers in Each Node II
- 一晚上 -- Populating Next Right Pointers in Each Node II
- Populating Next Right Pointers in Each Node II