import java.util.*; /* * public class TreeNode { * int val = 0; * TreeNode left = null; * TreeNode right = null; * public TreeNode(int val) { * this.val = val; * } * } */ public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ public int widthOfBinaryTree (TreeNode root) { // write code here if (root == null) return 0; HashMap<Integer, int[]> map = new HashMap<>(); dfs(root, map, 1, 1); int res = 0; for (HashMap.Entry<Integer, int[]> e : map.entrySet()) { res = Math.max(res, e.getValue()[1] - e.getValue()[0] + 1); } return res; } private void dfs(TreeNode root, HashMap<Integer, int[]> map, int curId, int depth) { if (!map.containsKey(depth)) map.put(depth, new int[] {Integer.MAX_VALUE, Integer.MIN_VALUE}); map.get(depth)[0] = Math.min(map.get(depth)[0], curId); map.get(depth)[1] = Math.max(map.get(depth)[1], curId); if (root.left != null) { dfs(root.left, map, curId * 2, depth + 1); } if (root.right != null) { dfs(root.right, map, curId * 2 + 1, depth + 1); } } }