Back to course home
0% completed
Vote For New Content
Two Approaches to Find Maximum Width: Including & Excluding Null Nodes
The Whiz
Jan 24, 2025
Case 1: Including Null Nodes
public int widthOfBinaryTree (TreeNode root) { if (root == null) return 0; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int max = 0; while (!queue.isEmpty()) { int size = queue.size(); // Check if all nodes at this level are null boolean allNull = queue.stream().allMatch(Objects::isNull); // Calculate level size int levelSize = getLevelSize(queue); max = Math.max(max, levelSize); // Process nodes at the current level for (int i = 0; i < size; i++) { TreeNode node = queue.poll(); if (node != null) { queue.offer(node.left); queue.offer(node.right); } else if (!allNull) { // Add placeholders for null nodes if there are non-null nodes queue.offer(null); queue.offer(null); } } } return max; } private int getLevelSize (Queue<TreeNode> queue) { List<TreeNode> list = new ArrayList<>(queue); // Convert queue to list int left = 0; int right = list.size() - 1; // Trim nulls from both ends of the list while (left <= right && list.get(left) == null) { left++; } while (left <= right && list.get(right) == null) { right--; } // Width is the number of non-null positions return right - left + 1; }
Case 2: Excluding Null Nodes
public int widthOfBinaryTree (TreeNode root) { Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int max = Integer.MIN_VALUE; while (!queue.isEmpty()) { int size = queue.size(); max = Math.max(max, size); for (int i = 0; i < size; i++) { TreeNode element = queue.poll(); if (element.left != null) { queue.offer(element.left); } if (element.right != null) { queue.offer(element.right); } } } return max; }
0
0
Comments
Comments
On this page