Simple Iterative solution , beats most O(n)


  • 0
    T

    The idea is to do a BFS and at the end of the row, insert a null.
    Now just keep connecting to the next item in the 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();
                    queue.offer(visit.left);
                    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.