题意就是给一棵二叉树,让你变成这个样子:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ / \
4->5->6->7 -> NULL
思路是:层次遍历+添加next节点
public class Solution {
public void connect(TreeLinkNode root) {
Queue<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
int count=0;
int temp=0;
if(root!=null)
{
q.offer(root);
count++;
}
while(!q.isEmpty()){
TreeLinkNode tempnode=q.poll();
count--;
tempnode.next=null;
if(tempnode.left!=null){
temp++;
q.offer(tempnode.left);
}
if(tempnode.right!=null){
temp++;
q.offer(tempnode.right);
}
while(count>0){
TreeLinkNode tempnode2=q.poll();
tempnode.next=tempnode2;
tempnode=tempnode.next;
if(tempnode.left!=null){
temp++;
q.offer(tempnode.left);
}
if(tempnode.right!=null){
temp++;
q.offer(tempnode.right);
}
count--;
}
count=temp;
temp=0;
}
}
}