1、前言
题目描述2、思路
用116题的思路。
3、代码
/*
// Definition for a Node.
class Node {
public int val;
public Node left;
public Node right;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _left, Node _right, Node _next) {
val = _val;
left = _left;
right = _right;
next = _next;
}
};
*/
class Solution {
public Node connect(Node root) {
if(root == null){
return root;
}
LinkedList<Node> queue = new LinkedList<>();
queue.offer(root);
while(!queue.isEmpty()){
int size = queue.size();
Node p = queue.get(0);
for(int i = 1; i < size; i++){
Node q = queue.get(i);
p.next = q;
p = q;
}
for(int i = 0; i < size; i++){
Node cur = queue.poll();
if(cur.left != null){
queue.offer(cur.left);
}
if(cur.right != null){
queue.offer(cur.right);
}
}
}
return root;
}
}
网友评论