Easy BFS solution but it is not inplace. Don't click me :)


  • 0
    
        public void connect(TreeLinkNode root) {
            if(root == null){
                return;
            }
            Queue<TreeLinkNode> queue = new LinkedList<>();
            queue.offer(root);
            while(!queue.isEmpty()){
                int len = queue.size();
                for(int i = 0; i < len; i++){
                    TreeLinkNode node = queue.poll();
                    if(node.left != null) queue.offer(node.left);
                    if(node.right != null) queue.offer(node.right);
                    if(i == len-1){
                        node.next = null;
                    }else{
                        node.next = queue.peek();
                    }
                }
            }
        }
    
    ```

  • 0
    T

    But using queue, this is not O(1) in space


  • 0

    @toanngosy yes, you are right. I ignored this note "You may only use constant extra space."


Log in to reply
 

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