Easy JAVA solution using Two Queues


#1

/**

  • 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 q = new LinkedList();
    Queue p = new LinkedList();
    q.add(root);

    while(!q.isEmpty()|| !p.isEmpty()){
        while(q.size()>0){
            if(q.peek().left!=null){
                p.add(q.peek().left);
            }
            
            if(q.peek().right!=null){
                p.add(q.peek().right);
            }
            if(q.size()>=2){
             q.poll().next=q.peek();
            }else
            q.poll();
        }
        while(p.size()>0){
            if(p.peek().left!=null){
                q.add(p.peek().left);
            }
            
            if(p.peek().right!=null){
                q.add(p.peek().right);
            }
            if(p.size()>=2){
             p.remove().next=p.peek();
            }else
            p.poll();
    }
    }
    

}
}