Simple Java Solution


  • 0
    Z
     
    public class Solution {
        public void connect(TreeLinkNode root) {
            if (root == null) {
                return;
            }
    
            LinkedList<TreeLinkNode> queue = new LinkedList<>();
            queue.offer(root);
            while (!queue.isEmpty()) {
                int size = queue.size();
                while (size-- > 0) {
                    TreeLinkNode node = queue.poll();
                    node.next = size == 0 ? null : queue.peek();
    
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
            }
        }
    
    }
    

  • 0
    J

    The question requires a constant extra space. So I think queue can not be used in the question.


  • 0
    Z

    @Jiminwen thank you for mentioning that, I didn't notice.


Log in to reply
 

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