求二叉树最大宽度


import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;

/**
* 二叉树最大宽度
*/
public class TreeMaxWidth {

/**
* 不使用HashMap实现
*
* @param head 二叉树的头节点
* @return 最大宽度
*/
public int treeMaxWidthNoMap(Node head) {
int maxWidth = 0;
if (head == null) {
return maxWidth;
}
// 用队列实现
Queue<Node> queue = new LinkedList<>();
queue.add(head);
Node curEnd = head;
Node nextEnd = null;
int curWidth = 0;
while (!queue.isEmpty()) {
Node node = queue.poll();
if (node.left != null) {
queue.add(node.left);
nextEnd = node.left;
}
if (node.right != null) {
queue.add(node.right);
nextEnd = node.right;
}
curWidth++;
if (node == curEnd) {
maxWidth = Math.max(maxWidth, curWidth);
curWidth = 0;
curEnd = nextEnd;
}
}
return maxWidth;
}

/**
* 使用HashMap实现
*
* @param head 二叉树的头节点
* @return 最大宽度
*/
public int treeMaxWidthUseMap(Node head) {
int maxWidth = 0;
if (head == null) {
return maxWidth;
}
// 用队列实现
Queue<Node> queue = new LinkedList<>();
queue.add(head);
// 节点对应在哪一层
HashMap<Node, Integer> levelMap = new HashMap<>();
levelMap.put(head, 1);
int curWidth = 0;
int level = 1;
while (!queue.isEmpty()) {
Node node = queue.poll();
int curLevel = levelMap.get(node);
if (node.left != null) {
queue.add(node.left);
levelMap.put(node.left, levelMap.get(node) + 1);
}
if (node.right != null) {
queue.add(node.right);
levelMap.put(node.right, levelMap.get(node) + 1);
}
if (curLevel == level) {
curWidth++;
} else {
maxWidth = Math.max(maxWidth, curWidth);
level = curLevel;
curWidth = 1;
}
}
maxWidth = Math.max(maxWidth, curWidth);
return maxWidth;
}

/**
* 二叉树结构
*/
public static class Node {

public int value;

public Node left;

public Node right;

public Node(int value) {
this.value = value;
}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */
原文地址:https://www.cnblogs.com/laydown/p/12946040.html