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

Populating Next Right Pointers in Each Node II

2015-08-06 15:05 555 查看
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

思路和上一个相似,只是加入了对左右是否为空的判断。

public void connect(TreeLinkNode root) {
if(root==null)
return;
TreeLinkNode parent=root;
TreeLinkNode next,pre;
while(parent!=null){
next=null;
pre=null;
while(parent!=null){
if(next==null)
next=parent.left!=null?parent.left:parent.right;
if(parent.left!=null){
if(pre==null)
pre=parent.left;
else{
pre.next=parent.left;
pre=pre.next;
}
}
if(parent.right!=null){
if(pre==null)
pre=parent.right;
else{
pre.next=parent.right;
pre=pre.next;
}
}
parent=parent.next;
}
parent=next;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: