plantuml最大宽度_求二叉树最大宽度

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 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 queue = new LinkedList<>();

queue.add(head);

// 节点对应在哪一层

HashMap 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;

}

}

}

/* 如有意见或建议,欢迎评论区留言;如发现代码有误,欢迎批评指正 */

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值