[力扣算法题]《117. 填充每个节点的下一个右侧节点指针 II》
class Solution {
public static Node connect(Node root) {
// the second type: failed(It turns a little bit easy for me, but I still failed because I dont't quite understand with the usage of Queue(a Java abstract class), especially its instantiation.)
if(root == null)return null;
// 28 line error change to the following two lines
Queue<Node> queue = new LinkedList<Node>();
// Queue<Node> queue = new Queue<Node>(); // error
// error reason: Queue is the Abstract class, can not be instantiated,
// should be instantiated by its subClass, name LinkedList, folling this:
// Queue queue = new LinkedList();
// Queue<Node> queue = new LinkedList<Node>(); // in this case
Node f = null;
queue.offer(root);
while(!queue.isEmpty()){
int len = queue.size();
for(int i = 1; i <= len; ++i){
Node n = queue.poll();
if(n.left != null){
queue.offer(n.left);
}
if(n.right != null){
queue.offer(n.right);
}
if(i != 1){
f.next = n;
}
f = n;
}
}
return root;
} // the second type: failed
// the first type: failed(it's difficult for me!)
// // following the official website
// public Node connect(Node root) {
// if(root == null)return null;
// // Queue<Node> queuq = new LinkedList<Node>();
// Queue<Node> queue = new LinkedList<Node>();
// queue.offer(root);
// while(!queue.isEmpty()){
// int length = queue.size();
// Node last = null;
// // for(int i = 1; i < len; ++i){
// // for(int i = 1; i <= lenght; ++i){ // error
// for(int i = 1; i <= length; ++i){
// Node f = queue.poll();
// if(f.left != null){
// queue.offer(f.left);
// }
// if(f.right != null){
// queue.offer(f.right);
// }
// if(i != 1){
// // last = f; // error
// last.next = f;
// }
// // if(i > 1){
// // last.next = f;
// // }
// last = f;
// }
// }
// return root;
// }
// // following the official website
// error
// public Node connect(Node root) {
// Node head = new Node(-1, null, root, null);
// wfs(head.right);
// return head.right;
// }
// public static void wfs(Node root){
// if(root == null || root.right == null){
// // root.next = null;
// return;
// } // 出口
// // while(root.right != null){
// // while(root.right == null){
// wfs(root.left);
// wfs(root.right);
// root.next = root.right;
// // }
// // wfs(root.left);
// // wfs(root.right);
// } // error
}