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

【LeetCode】Populating Next Right Pointers in Each Node

2014-11-29 15:26 239 查看

编程小记,已供重温!!

PopulatingNextRightPointersinEachNode

Givenabinarytree

structTreeLinkNode{
TreeLinkNode*left;
TreeLinkNode*right;
TreeLinkNode*next;
}

Populateeachnextpointertopointtoitsnextrightnode.Ifthereisnonextrightnode,thenextpointershouldbesetto
NULL
.

Initially,allnextpointersaresetto
NULL
.

Note:

Youmayonlyuseconstantextraspace.

Youmayassumethatitisaperfectbinarytree(ie,allleavesareatthesamelevel,andeveryparenthastwochildren).

Forexample,
Giventhefollowingperfectbinarytree,

1
/\
23
/\/\
4567


Aftercallingyourfunction,thetreeshouldlooklike:

1->NULL
/\
2->3->NULL
/\/\
4->5->6->7->NULL

先不管空间复杂度,最直接想到的方法解决。

此题,我的第一反映是广度优先遍历。按层访问。每一层自左向右按顺序链接!需要借助于队列来实现。(其实这种方式还适合解决不是perfectbinarytree的题目,^_^,PopulatingNextRightPointersinEachNodeII就是这样的问题。)这种实现方法的空间复杂度是o(n)

思路一的实现方式:


publicstaticvoidconnect(TreeLinkNoderoot){
if(root==null){
return;
}
intcount=0;
Queue<TreeLinkNode>queue=newLinkedList<TreeLinkNode>();
queue.add(root);
count=queue.size();
while(!queue.isEmpty()){
TreeLinkNodetop=queue.poll();
count--;
if(top.left!=null){
queue.add(top.left);
}
if(top.right!=null){
queue.add(top.right);
}
if(count==0){
top.next=null;
count=queue.size();
}
else{
top.next=queue.peek();
}
}

}


思路二是,我们仔细观察发现,链接分为2种情况:情况1是链接root节点的左子树与右子树。情况2是链接节点2的右子树与节点3的左子树。

12——》3
/\/\/\
2->345——》67
(1)(2)

剩余的就是选择一个普通的遍历方式。空间复杂度是O(logn)
思路二实现方式


publicstaticvoidtra(TreeLinkNoderoot){
if(root==null){
return;
}
Stack<TreeLinkNode>stack=newStack<>();
while(null!=root||!stack.isEmpty()){
while(null!=root){
stack.push(root);
          //visit
          System.out.println(root.val);
          //  
root=root.left;
}
root=stack.pop();root=root.right;
}
}


遍历的同时,链接2种。

publicstaticvoidconnect(TreeLinkNoderoot){
if(root==null){
return;
}
Stack<TreeLinkNode>stack=newStack<>();
while(null!=root||!stack.isEmpty()){
while(null!=root){
stack.push(root);
if(root.left!=null){
root.left.next=root.right;
if(root.next!=null){
root.right.next=root.next.left;
}
}
root=root.left;
}
root=stack.pop();
root=root.right;
}
}


考虑时间复杂度:
经过分析我们发现,只要是能够保证找到下一行的第一个节点以及当前行的下一个节点就可以了,所以,可以采用如下的方式实现:
思路3实现方法


publicstaticvoidconnect3(TreeLinkNoderoot){
if(root==null){
return;
}
TreeLinkNodenextLinkNode=null;
while(null!=root){
nextLinkNode=root;
while(nextLinkNode!=null){

if(nextLinkNode.left!=null){
nextLinkNode.left.next=nextLinkNode.right;
if(nextLinkNode.next!=null){
nextLinkNode.right.next=nextLinkNode.next.left;
}
}
nextLinkNode=nextLinkNode.left;
}
root=root.left;
}
}


空间复杂度为O(1)。


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: