代码拉取完成,页面将自动刷新
package com.binaryTree;
import org.omg.CORBA.MARSHAL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Queue;
// 求二叉树最宽的层有多少个节点(即二叉树的最大宽度)
public class TreeMaxWidth {
public static class Node {
public int value;
public Node left;
public Node right;
public Node(int data) {
this.value = data;
}
}
public static int maxWidth1(Node head){
if (head == null){
return 0;
}
Node curEnd = head; // 记录当前层的最后节点
Node nextEnd = null; // 记录下一层的最后节点
int count = 0; // count记录当前层的节点个数(宽度),因为由前面if判断知道,head不为null,故当前层的节点数为1
int max = 0; // 最后返回的最大宽度
Queue<Node> queue = new LinkedList<>();
queue.add(head);
while (!queue.isEmpty()){
Node cur = queue.poll();
count++; // 每从queue中poll节点但 cur!=curEnd(没遍历当前层的最后节点时),当前层的节点数count+1
if (cur.left != null){
queue.add(cur.left);
nextEnd = cur.left;
}
if (cur.right != null){
queue.add(cur.right);
nextEnd = cur.right;
}
if (cur == curEnd){
max = Math.max(max,count);
curEnd = nextEnd;
count = 0;
}
}
return max;
}
public static int maxWidth2(Node head){
if (head == null){
return 0;
}
Queue<Node> queue = new LinkedList<>();
queue.add(head);
int curLevel = 1; // 当前统计宽度的层数
Map<Node,Integer> map = new HashMap<>();
map.put(head,1);
int count = 0;
int max = 0;
while (!queue.isEmpty()){
Node cur = queue.poll();
int nodeLevel = map.get(cur); // cur节点所在层数
if (cur.left != null){
map.put(cur.left,nodeLevel+1);
queue.add(cur.left);
}
if (cur.right != null){
map.put(cur.right,nodeLevel+1);
queue.add(cur.right);
}
if (curLevel == nodeLevel){ // 当前统计宽度的层数与cur节点所在层数相等,节点数count +1
count++;
}else {
curLevel++;
max = Math.max(max,count);
count = 1;
}
}
max = Math.max(max,count);
return max;
}
// for test
public static Node generateRandomBST(int maxLevel, int maxValue) {
return generate(1, maxLevel, maxValue);
}
// for test
// level为当前创建节点的层数
public static Node generate(int level, int maxLevel, int maxValue) {
if (level > maxLevel || Math.random() < 0.5) {
return null;
}
Node head = new Node((int) (Math.random() * maxValue));
head.left = generate(level + 1, maxLevel, maxValue);
head.right = generate(level + 1, maxLevel, maxValue);
return head;
}
public static void main(String[] args) {
int maxLevel = 10;
int maxValue = 100;
int testTimes = 1000000;
System.out.println("test start:");
for (int i = 0; i < testTimes; i++) {
Node head = generateRandomBST(maxLevel, maxValue);
if (maxWidth1(head) != maxWidth2(head)) {
System.out.println("Oops!");
}
}
System.out.println("finish!");
}
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。