Simple Iterative Solution


  • 0
    T

    Idea is to do a BFS and and the end of the row, use null to make end of the row
    Now, while iterating, just point the current to the next in queue

        public void connect(TreeLinkNode root){
            if (null == root){
                return;
            }
    
            Queue<TreeLinkNode> queue = new LinkedList<>();
            queue.offer(root);
            queue.offer(null);
    
            while (!queue.isEmpty()){
                TreeLinkNode visit = queue.poll();
                if (null != visit){
                    visit.next = queue.peek();
                    if (null != visit.left)
                        queue.offer(visit.left);
    
                    if (null != visit.right)
                        queue.offer(visit.right);
                }else {
                    queue.offer(null);
                    if (queue.peek() == null){
                        break;
                    }
                }
            }
        }
    

Log in to reply
 

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