1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
|
class Solution { int ans = 0; Map<Integer, Integer> minIndex = new HashMap<>();
public int widthOfBinaryTree(TreeNode root) { dfs(root, 1, 0); return ans; }
private void dfs(TreeNode node, int index, int depth) { if (node == null) return; minIndex.putIfAbsent(depth, index); ans = Math.max(ans, index - minIndex.get(depth) + 1); dfs(node.left, index * 2, depth + 1); dfs(node.right, index * 2 + 1, depth + 1); } }
|