用了两种不同的方式,一个是基于队列加Map,一个是单独队列
queue+map
public static int maxWidthWithMap(Node head){
if(head == null){
return 0;
}
//这里是放Node入队列的
Queue<Node> queue = new LinkedList<>();
//这里主要是为了保存Node的层级的
HashMap<Node,Integer> map = new HashMap<>();
queue.add(head);
map.put(head,1);
//这个是要返回的值
int max = 0;
int curLevel = 1;
//当前层级是curLevel的宽度是多少
int curLevelNodes = 0 ;
while (!queue.isEmpty()){
Node cur = queue.poll();
int curNodeLevel = map.get(cur);
if(cur.left != null){
map.put(cur.left,curNodeLevel+1);
queue.add(cur.left);
}
if(cur.right != null){
map.put(cur.right,curNodeLevel+1);
queue.add(cur.right);
}
//如果当前层级和从map获取的层级节点信息相等,说明还在同一层,宽度加1
if(curLevel == curNodeLevel){
curLevelNodes ++;
}else{
//如果跳到下一层级了,那么记录宽度的应该初始化成1,还需要把层级加1
max = Math.max(max,curLevelNodes);
curLevel ++;
curLevelNodes = 1;
}
}
max = Math.max(max,curLevelNodes);
return max;
}
queue
public static int maxWidthNoMap(Node head){
if(head == null){
return 0;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
Node curEnd = head;
Node nextEnd = null;
int max = 0;
int curLevelNodes = 0;
while (!queue.isEmpty()){
Node cur = queue.poll();
if(cur.left != null){
queue.add(cur.left);
nextEnd = cur.left;
}
if(cur.right != null){
queue.add(cur.right);
nextEnd = cur.right;
}
curLevelNodes ++;
if(cur == curEnd){
curEnd = nextEnd;
max = Math.max(max,curLevelNodes);
curLevelNodes = 0;
}
}
// 不用加这行,因为while里面是弹出node就算出来了,和map的那种方式有区别
// max = Math.max(max,curLevelNodes);
return max;
}
Node基础节点信息
public static class Node{
private int value;
private Node left;
private Node right;
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
public Node getLeft() {
return left;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public void setRight(Node right) {
this.right = right;
}
}