3ms Java solution with queue


  • 0
    Y
    public class Solution {
        public void connect(TreeLinkNode root) {
            // 6:27pm - 6:35pm
            // iterative, level-order traversal using queue
            if (root == null) {
                return;
            }
            LinkedList<TreeLinkNode> queue = new LinkedList<TreeLinkNode>();
            queue.offer(root);
            while (queue.size() != 0) {
                int size = queue.size();
                TreeLinkNode prev = null;
                for (int i = 0; i < size; i++) {
                    TreeLinkNode curr = queue.poll();
                    if (prev != null) {
                        prev.next = curr;
                    }
                    prev = curr;
                    if (curr.left != null) {
                        queue.offer(curr.left);
                    }
                    if (curr.right != null) {
                        queue.offer(curr.right);
                    }
                }
                prev.next = null;
            }
        }
    }

Log in to reply
 

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