package tree;
class TreeNodeq{
int value;
TreeNodeq left;
TreeNodeq right;
TreeNodeq nextright;
public TreeNodeq(int value, TreeNodeq left, TreeNodeq right,
TreeNodeq nextright) {
this.value = value;
this.left = left;
this.right = right;
this.nextright = nextright;
}
}
public class Connectnodesatsamelevel {
/**
* 连接的核心代码
* @param args
*/
public static void connect(TreeNodeq root){
if(root==null) return;
TreeNodeq p = root;
while(p!=null){
TreeNodeq q = p;
while(q!=null){
if(q.left!=null){
if(q.right!=null){
q.left.nextright = q.right;
}else{
q.left.nextright = getNextRight(q);
}
}
if(q.right!=null){
q.right.nextright = getNextRight(q);
}
q = q.nextright;
}
if(p.left!=null){
p = p.left;
}else if(p.right!=null){
p = p.right;
}else{
p = getNextRight(p);
}
}
}
private static TreeNodeq getNextRight(TreeNodeq q) {
TreeNodeq temp = q.nextright;
while(temp!=null){
if(temp.left!=null){
return temp.left;
}
if(temp.right!=null){
return temp.right;
}
temp = temp.nextright;
}
return null;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}