package com.fishercoder.solutions;

import com.fishercoder.common.classes.TreeLinkNode;

public class _116 {
    public static class Solution1 {
        /**
         * credit: https://discuss.leetcode.com/topic/1106/o-1-space-o-n-complexity-iterative-solution
         * based on level order traversal
         */
        public void connect(TreeLinkNode root) {

            TreeLinkNode head = null; //head of the next level
            TreeLinkNode prev = null; //the leading node on the next level
            TreeLinkNode curr = root;  //current node of current level

            while (curr != null) {
                while (curr != null) { //iterate on the current level
                    //left child
                    if (curr.left != null) {
                        if (prev != null) {
                            prev.next = curr.left;
                        } else {
                            head = curr.left;
                        }
                        prev = curr.left;
                    }
                    //right child
                    if (curr.right != null) {
                        if (prev != null) {
                            prev.next = curr.right;
                        } else {
                            head = curr.right;
                        }
                        prev = curr.right;
                    }
                    //move to next node
                    curr = curr.next;
                }
                //move to next level
                curr = head;
                head = null;
                prev = null;
            }
        }
    }
}

@@ -82,16 +82,70 @@
 kNode;%0A%0A
+import java.util.LinkedList;%0Aimport java.util.Queue;%0A%0A
 public c
@@ -1664,11 +1664,1022 @@
  %7D%0A    %7D
+%0A%0A    public static class Solution2 %7B%0A        /**%0A         * My complete original solution on 10/10/2021.%0A         */%0A        public TreeLinkNode connect(TreeLinkNode root) %7B%0A            if (root == null) %7B%0A                return null;%0A            %7D%0A            Queue%3CTreeLinkNode%3E queue = new LinkedList%3C%3E();%0A            queue.offer(root);%0A            while (!queue.isEmpty()) %7B%0A                int size = queue.size();%0A                for (int i = 0; i %3C size; i++) %7B%0A                    TreeLinkNode curr = queue.poll();%0A                    if (i %3C size - 1) %7B%0A                        curr.next = queue.peek();%0A                    %7D else %7B%0A                        curr.next = null;%0A                    %7D%0A                    if (curr.left != null) %7B%0A                        queue.offer(curr.left);%0A                    %7D%0A                    if (curr.right != null) %7B%0A                        queue.offer(curr.right);%0A                    %7D%0A                %7D%0A            %7D%0A            return root;%0A        %7D%0A    %7D
 %0A%7D%0A

refactor 116