您的位置:首页 > Web前端 > Node.js

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,

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)
思路:
在上一次已经连接好的情况下,再进行下一层的连接。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: