1. // 初始化:当前层数,当前层节点个数,全局最大个数,Map(head,1)头节点在一层,头节点进队列。
    2. // 头节点出队列,左右孩子进队列,Map(children,2)设置层数,更新全局最大数,
    3. // 设置为二层,重置当前层节点数。周而复始。
    4. //通过层数变更来更新当前层节点数,更新最大值
    5. public static int MaxWidth(Node head){
    6. if( head == null){
    7. return 0;
    8. }
    9. // 当前层数
    10. int curLevel = 1;
    11. // 当前层节点数量
    12. int nodes = 0;
    13. // 全局节点最大数量
    14. int max = Integer.MIN_VALUE;
    15. // 放入头,设置第一层
    16. HashMap<Node, Integer> hashMap = new HashMap<>();
    17. hashMap.put(head, 1);
    18. // 初始队列
    19. Queue<Node> queue = new LinkedList<Node>();
    20. queue.add(head);
    21. while(!queue.isEmpty()){
    22. // 取值
    23. Node cur = queue.poll();
    24. // 取当前值层级
    25. int level = hashMap.get(cur);
    26. // 同一层,节点个数++
    27. if(level == curLevel){
    28. nodes++;
    29. }else{
    30. // 做清算max,更新下一层,节点个数为一,因为已经是下一层节点
    31. max = Math.max(max, nodes);
    32. curLevel++;
    33. nodes = 1;
    34. }
    35. if(cur.left != null){
    36. hashMap.put(cur.left, level+1);
    37. queue.add(cur.left);
    38. }
    39. if(cur.right != null){
    40. hashMap.put(cur.right, level+1);
    41. queue.add(cur.right);
    42. }
    43. }
    44. // 最后再清算一次,或许最后一层节点数量最多。但因为是最后一层触发不了清算。
    45. max = Math.max(max, nodes);
    46. return max;
    47. }