1 Star 1 Fork 0

xuzhixing/算法学习

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
TreeMaxWidth.java 3.65 KB
一键复制 编辑 原始数据 按行查看 历史
xuzhixing 提交于 2022-05-07 21:53 +08:00 . 算法学习与总结
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!");
}
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Java
1
https://gitee.com/xuleiProject/algorithm-learning.git
git@gitee.com:xuleiProject/algorithm-learning.git
xuleiProject
algorithm-learning
算法学习
master

搜索帮助