Java O(n) BFS one queue clean solution


  • 0

    change the val of node to be the index to save space. The value is useless. All we need is just the index.

    class Solution {
        public int widthOfBinaryTree(TreeNode root) {
            if (root == null) {
                return 0;
            }
            LinkedList<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
            root.val = 0;
            int max = 1;
            while (!queue.isEmpty()) {
                int size = queue.size();
                max = Math.max(max, queue.peekLast().val - queue.peekFirst().val + 1);
                for (int i = 0; i < size; i++) {
                    root = queue.poll();
                    if (root.left != null) {
                        root.left.val = root.val * 2;
                        queue.offer(root.left);
                    }
                    if (root.right != null) {
                        root.right.val = root.val * 2 + 1;
                        queue.offer(root.right);
                    }
                }
            }
            return max;
        }
    }

Log in to reply
 

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