|
| 1 | +import java.util.ArrayDeque; |
| 2 | +import java.util.Queue; |
| 3 | + |
| 4 | +import DS.TreeNode; |
| 5 | + |
| 6 | +/* |
| 7 | + // Definition of TreeNode: |
| 8 | + class TreeNode { |
| 9 | + public int val; |
| 10 | + public TreeNode left; |
| 11 | + public TreeNode right; |
| 12 | + public TreeNode(int val) { |
| 13 | + this.val = val; |
| 14 | + } |
| 15 | + } |
| 16 | + */ |
| 17 | + |
| 18 | +public class WidestBinaryTreeLevel { |
| 19 | + public class Pair { |
| 20 | + TreeNode node; |
| 21 | + int index; |
| 22 | + public Pair(TreeNode node, int index) { |
| 23 | + this.node = node; |
| 24 | + this.index = index; |
| 25 | + } |
| 26 | + } |
| 27 | + |
| 28 | + public int widestBinaryTreeLevel(TreeNode root) { |
| 29 | + if (root == null) { |
| 30 | + return 0; |
| 31 | + } |
| 32 | + int maxWidth = 0; |
| 33 | + Queue<Pair> queue = new ArrayDeque<>(); |
| 34 | + queue.offer(new Pair(root, 0)); // Stores (node, index) pairs. |
| 35 | + while (!queue.isEmpty()) { |
| 36 | + int levelSize = queue.size(); |
| 37 | + // Set the 'leftmostIndex' to the index of the first node in |
| 38 | + // this level. Start 'rightmostIndex' at the same point as |
| 39 | + // 'leftmostIndex' and update it as we traverse the level, |
| 40 | + // eventually positioning it at the last node. |
| 41 | + int leftmostIndex = queue.peek().index; |
| 42 | + int rightmostIndex = leftmostIndex; |
| 43 | + // Process all nodes at the current level. |
| 44 | + for (int j = 0; j < levelSize; j++) { |
| 45 | + Pair pair = queue.poll(); |
| 46 | + TreeNode node = pair.node; |
| 47 | + int i = pair.index; |
| 48 | + if (node.left != null) { |
| 49 | + queue.offer(new Pair(node.left, 2 * i + 1)); |
| 50 | + } |
| 51 | + if (node.right != null) { |
| 52 | + queue.offer(new Pair(node.right, 2 * i + 2)); |
| 53 | + } |
| 54 | + rightmostIndex = i; |
| 55 | + } |
| 56 | + maxWidth = Math.max(maxWidth, rightmostIndex - leftmostIndex + 1); |
| 57 | + } |
| 58 | + return maxWidth; |
| 59 | + } |
| 60 | +} |
0 commit comments