Java solution using one queue


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

Log in to reply
 

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