宽度优先遍历就是从上到下,从左到右依次遍历就行。
可以使用队列来做。
先将头结点放入队列,
重复下面的行为。
{从队列中弹出一个节点,并打印。
如果弹出的节点有左节点,就将左节点放入队列中,
如果弹出的节点有右节点,就将右节点放入队列中。先左后右。
}
public static void widthPrioritySearch(NodeTwo node) {
if(node==null) {
return ;
}
Queue<NodeTwo> queue = new LinkedList<>();
queue.add(node);
while(!queue.isEmpty()) {
NodeTwo cur = queue.poll();
System.out.println(cur.value);
if(cur.left != null) {
queue.add(cur.left);
}
if(cur.right != null) {
queue.add(cur.right);
}
}
}
求二叉树的最大宽度:
思路:记录每一个节点所在的层,并且用一个变量记录每一层有多少个节点。
记录每一个节点所在的层最好使用的就是hash表。
public static int widthMax(NodeTwo node) {
if(node==null) {
return 0;
}
Queue<NodeTwo> queue = new LinkedList<>();
HashMap<NodeTwo,Integer> map = new HashMap<>();
//使用hash表来记录每个节点所在的层数
map.put(node, 1);
int currentLevel = 1;
int currentNodes = 0;
int max = Integer.MIN_VALUE;
queue.add(node);
while(!queue.isEmpty()) {
NodeTwo cur = queue.poll();
int level = map.get(cur);
if(currentLevel == level) {
//弹出节点所在的层数等于现在的层数,
//当前层数的节点数加1
currentNodes++;
}else {
//如果弹出节点的层数不等于当前的层数
//那么就是这个节点是下一层的了,上一层的节点个数已经统计好了
max = Math.max(max, currentNodes);
//
currentLevel++;
currentNodes = 1;
//当前层的节点数置为1,
}
// System.out.println(cur.value);
if(cur.left != null) {
queue.add(cur.left);
map.put(cur.left, map.get(cur)+1);
}
if(cur.right != null) {
queue.add(cur.right);
map.put(cur.right, map.get(cur)+1);
}
}
//在最后一个节点弹出的时候有可能满足currentLevel == level
//就不会将最后一层的节点数与最大值相比较
//所以弹出所有节点之后需要再将最后一层的节点数和最大值进行比较
return max = Math.max(max, currentNodes);
}