题意:
给一个二叉树,将其next指针设置为其水平右边相邻的那个结点,没有则设置为空
分析:
the code which i wrote for the 116 still work.
/**
* 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) {
Queue<TreeLinkNode> q = new LinkedList<>();
if(root == null)
return;
q.offer(root);
while(!q.isEmpty()){
int size = q.size();
for(int i=0; i<size; i++){
TreeLinkNode node = q.poll();
if(i != size-1)
node.next = q.peek();
if(node.left != null){
q.offer(node.left);
}
if(node.right != null){
q.offer(node.right);
}
}
}
}
}