二叉树层次遍历的变种
用辅助队列,一层一层地遍历每一层的元素,先出队的元素的next是后一个出队的元素
每一层最后一个元素的next=null
II的解法也一样
public void connect(TreeLinkNode root) {
Queue<TreeLinkNode> Q = new ArrayDeque<TreeLinkNode>();
if(root == null)return;
Q.offer(root);
int count = 1;
while(!Q.isEmpty()){
int nextCount = 0;
for(int i =0;i<count;i++){
TreeLinkNode p = Q.poll();
if(p.left != null){
Q.offer(p.left);
nextCount++;
}
if(p.right != null){
Q.offer(p.right);
nextCount++;
}
TreeLinkNode q = null;
if(i < count-1)q = Q.peek();
p.next = q;
}
count = nextCount;
}
}