一开始用递归,发现有些条件不满足,后来用队列的方法就accept了。
/**
* Definition for binary tree with next pointer.
* public class TreeLinkNode {
* int val;
* TreeLinkNode left, right, next;
* TreeLinkNode(int x) { val = x; }
* }
*/
import java.util.LinkedList;
public class Solution {
public void connect(TreeLinkNode root) {
if(root==null){
return;
}
LinkedList<TreeLinkNode> q=new LinkedList<TreeLinkNode>();
TreeLinkNode p;
q.offer(root);
while((p=q.poll())!=null){
work(p);
if(p.left!=null){
q.offer(p.left);
}
if(p.right!=null){
q.offer(p.right);
}
}
}
public void work(TreeLinkNode root) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(root==null){
return;
}
TreeLinkNode temp=root.next ;
while(temp!=null){
if(temp.left==null && temp.right==null){
temp=temp.next;
}
else{
temp=(temp.left==null)?temp.right:temp.left;
break;
}
}
if(root.left!=null){
root.left.next=root.right==null?temp:root.right;
}
if(root.right!=null){
root.right.next=temp;
}
}
}