Java Solution using two queues


  • 0
    R
    public void connect(TreeLinkNode root) {
            if(root==null)  return ;
            Queue<TreeLinkNode> q = new LinkedList<>();
            q.offer(root);
            while(!q.isEmpty()){
                Queue<TreeLinkNode> newq = new LinkedList<>();      //newq restore the nodes in next level.
                while(!q.isEmpty()){
                    TreeLinkNode node = q.poll();
                    if(q.isEmpty()) node.next=null;
                    else node.next = q.peek();
                    if(node.left!=null)     newq.offer(node.left);
                    if(node.right!=null)    newq.offer(node.right);
                }
                q=newq;        // assign newq to q to start next stage
            }
        }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.