这题没啥难度,主要是仔细了
/**
* 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) {
if(root == null){
return;
}
int k = 0;
int length = (int)Math.pow(2, k);
LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
queue.add(root);
TreeLinkNode preNode = null;
while (!queue.isEmpty()){
TreeLinkNode node = queue.remove();
if(node.left != null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
if(preNode != null){
preNode.next=node;
}
if(length == 1){
length = (int)Math.pow(2, ++k);
node.next=null;
preNode = null;
}else{
preNode = node;
length--;
}
}
}
}