// 初始化:当前层数,当前层节点个数,全局最大个数,Map(head,1)头节点在一层,头节点进队列。// 头节点出队列,左右孩子进队列,Map(children,2)设置层数,更新全局最大数,// 设置为二层,重置当前层节点数。周而复始。//通过层数变更来更新当前层节点数,更新最大值public static int MaxWidth(Node head){ if( head == null){ return 0; } // 当前层数 int curLevel = 1; // 当前层节点数量 int nodes = 0; // 全局节点最大数量 int max = Integer.MIN_VALUE; // 放入头,设置第一层 HashMap<Node, Integer> hashMap = new HashMap<>(); hashMap.put(head, 1); // 初始队列 Queue<Node> queue = new LinkedList<Node>(); queue.add(head); while(!queue.isEmpty()){ // 取值 Node cur = queue.poll(); // 取当前值层级 int level = hashMap.get(cur); // 同一层,节点个数++ if(level == curLevel){ nodes++; }else{ // 做清算max,更新下一层,节点个数为一,因为已经是下一层节点 max = Math.max(max, nodes); curLevel++; nodes = 1; } if(cur.left != null){ hashMap.put(cur.left, level+1); queue.add(cur.left); } if(cur.right != null){ hashMap.put(cur.right, level+1); queue.add(cur.right); } } // 最后再清算一次,或许最后一层节点数量最多。但因为是最后一层触发不了清算。 max = Math.max(max, nodes); return max; }