Java, BFS and node position


  • 0
    public int widthOfBinaryTree(TreeNode root) {
            Queue<TreeNode> queue = new LinkedList<>();
            queue.add(root);
            Map<TreeNode, Integer> map = new HashMap<>();
            map.put(root, 1);
            int size = 1;
            int max = 1;
    
            while(!queue.isEmpty()) {
                int curSize = 0;
                int firstPosition = 0;
                TreeNode current = null;
                for (int i = 0; i < size; i++) {
                    current = queue.poll();
                    if(i == 0) firstPosition = map.get(current);
                    if(current.left != null) {
                        ++curSize;
                        map.put(current.left, 2 * map.get(current));
                        queue.add(current.left);
                    }
                    if(current.right != null) {
                        ++curSize;
                        map.put(current.right, 2 * map.get(current) + 1);
                        queue.add(current.right);
                    }
                }
                size = curSize;
                int levelSize = map.get(current) - firstPosition + 1;
                max = levelSize > max ? levelSize : max;
            }
            return max;
        }
    

Log in to reply
 

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