/**
* 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) {
//依然采用深度优先的思想
Queue<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
if(root==null)
return ;
q.offer(root);
int size=q.size();
int count=0;
TreeLinkNode temp=null;
TreeLinkNode tail=null;
while(!q.isEmpty())
{
temp=q.poll();
if(temp.left!=null)
q.offer(temp.left);
if(temp.right!=null)
q.offer(temp.right);
if(count!=0)
{
tail.next=temp;
}
count++;
if(count==size)
{
temp.next=null;
count=0;
size=q.size();
}
tail=temp;
}
}
}