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

[Leetcode] Populating Next Right Pointers in Each Node

2015-07-25 11:57 513 查看
因为有了next指针,所以访问过的每一层都是可以遍历的,同样的方式可以得到下一层的情况

/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
*     int val;
*     TreeLinkNode left, right, next;
*     TreeLinkNode(int x) { val = x; }
* }
*/
public class Solution {
public void connect(TreeLinkNode root) {
TreeLinkNode head=root;
while(head!=null){
TreeLinkNode tmphead=head;
head=null;
TreeLinkNode pre=null;
while(tmphead!=null){
if(tmphead.left!=null){
if(head==null){
pre=head=tmphead.left;
}
else{
pre.next=tmphead.left;
pre=tmphead.left;
}
}
if(tmphead.right!=null){
if(head==null){
pre=head=tmphead.right;
}else{
pre.next=tmphead.right;
pre=tmphead.right;
}
}
tmphead=tmphead.next;
}
}
}
}


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