求二叉树最宽的层有多少个节点

智数追光
• 阅读 948

一、思路:

在按层遍历的基础上进行改写

(1)准备currentLevelEnd(表示当前层的结束节点)、nextLevelEnd(表示下一层的结束节点)、currentWeight(表示当前层的宽度)、maxWeight(表示最大宽度)四个变量。

(2)currentLevelEnd修改为二叉树的头节点(其他均为默认值),头节点入队列。

(3)从队列中弹出一个节点,每出队一个节点则currentWeight加一,出队节点有左孩子则左孩子入队,有右孩子则右孩子入队,有节点入队则将nextLevelEnd修改为当前入队的节点(为下一层查找做准备)。

(4)判断第3步出队的节点是否等于currentLevelEnd。

是,则修改maxWeight为当前最大宽度,currentWeight重置,currentLevelEnd修改为nextLevelEnd,nextLevelEnd重置;

否,则继续执行第3步。

(5)一直执行第3、4步,直到队列为空。

/**
 * @author Java和算法学习:周一
 */
public static int treeMaxWidth(Node head) {
    if (head == null) {
        return 0;
    }

    Queue<Node> queue = new LinkedList<>();
    Node currentLevelEnd = head;
    Node nextLevelEnd = null;
    int currentWidth = 0;
    int maxWidth = 0;

    queue.offer(head);
    while (!queue.isEmpty()) {
        Node current = queue.poll();
        // 每次从队列中弹出节点时,当前层的宽度都加一
        currentWidth++;

        // 有孩子节点入队时就修改下一层的结束节点
        if (current.left != null) {
            queue.offer(current.left);
            nextLevelEnd = current.left;
        }
        if (current.right != null) {
            queue.offer(current.right);
            nextLevelEnd = current.right;
        }

        // 如果当前出队的节点是当前层的结束节点
        if (current == currentLevelEnd) {
            // 修改最大宽度
            maxWidth = Math.max(maxWidth, currentWidth);
            // 当前层宽度重置
            currentWidth = 0;
            // 当前层的结束节点修改,表明下一次循环时开始统计下一层的宽度
            currentLevelEnd = nextLevelEnd;
            // 下一层结束节点重置
            nextLevelEnd = null;
        }
    }

    return maxWidth;
}

二、对数器源码

/**
 * 对数器方法
 *     
 * @author Java和算法学习:周一
 */
public static int treeMaxWidth1(Node head) {
    if (head == null) {
        return 0;
    }
    Queue<Node> queue = new LinkedList<>();
    queue.add(head);
    // key:节点,value:节点在哪一层
    HashMap<Node, Integer> levelMap = new HashMap<>(16);
    levelMap.put(head, 1);
    // 当前来到哪一层
    int curLevel = 1;
    // 当前层的宽度
    int curLevelWidth = 0;
    // 最大宽度
    int max = 0;
    while (!queue.isEmpty()) {
        Node cur = queue.poll();
        int curNodeLevel = levelMap.get(cur);
        if (cur.left != null) {
            levelMap.put(cur.left, curNodeLevel + 1);
            queue.add(cur.left);
        }
        if (cur.right != null) {
            levelMap.put(cur.right, curNodeLevel + 1);
            queue.add(cur.right);
        }
        // 当前节点还是在当前层
        if (curNodeLevel == curLevel) {
            curLevelWidth++;
        } else {
            // 当前层已经遍历完毕
            max = Math.max(max, curLevelWidth);
            // 来到下一层
            curLevel++;
            // 当前节点已经是下一层的了,也就是下一层已经有一个节点了,宽度自然是1
            curLevelWidth = 1;
        }
    }
    // 最后一层的宽度没有和max比较,所以这里要再比较一次
    max = Math.max(max, curLevelWidth);
    return max;
}

本文全部代码:https://github.com/monday-pro/algorithm-study/blob/master/src/basic/binarytree/TreeMaxWidth.java

点赞
收藏
评论区
推荐文章
blmius blmius
4年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Oracle 分组与拼接字符串同时使用
SELECTT.,ROWNUMIDFROM(SELECTT.EMPLID,T.NAME,T.BU,T.REALDEPART,T.FORMATDATE,SUM(T.S0)S0,MAX(UPDATETIME)CREATETIME,LISTAGG(TOCHAR(
Wesley13 Wesley13
4年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Stella981 Stella981
4年前
List的Select 和Select().tolist()
List<PersondelpnewList<Person{newPerson{Id1,Name"小明1",Age11,Sign0},newPerson{Id2,Name"小明2",Age12,
Wesley13 Wesley13
4年前
VBox 启动虚拟机失败
在Vbox(5.0.8版本)启动Ubuntu的虚拟机时,遇到错误信息:NtCreateFile(\\Device\\VBoxDrvStub)failed:0xc000000034STATUS\_OBJECT\_NAME\_NOT\_FOUND(0retries) (rc101)Makesurethekern
Wesley13 Wesley13
4年前
FLV文件格式
1.        FLV文件对齐方式FLV文件以大端对齐方式存放多字节整型。如存放数字无符号16位的数字300(0x012C),那么在FLV文件中存放的顺序是:|0x01|0x2C|。如果是无符号32位数字300(0x0000012C),那么在FLV文件中的存放顺序是:|0x00|0x00|0x00|0x01|0x2C。2.  
Wesley13 Wesley13
4年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Wesley13 Wesley13
4年前
PHP创建多级树型结构
<!lang:php<?php$areaarray(array('id'1,'pid'0,'name''中国'),array('id'5,'pid'0,'name''美国'),array('id'2,'pid'1,'name''吉林'),array('id'4,'pid'2,'n
Wesley13 Wesley13
4年前
Java日期时间API系列36
  十二时辰,古代劳动人民把一昼夜划分成十二个时段,每一个时段叫一个时辰。二十四小时和十二时辰对照表:时辰时间24时制子时深夜11:00凌晨01:0023:0001:00丑时上午01:00上午03:0001:0003:00寅时上午03:00上午0
Stella981 Stella981
4年前
JavaScript常用函数
1\.字符串长度截取functioncutstr(str,len){vartemp,icount0,patrn/^\x00\xff/,strre"";for(vari
Python进阶者 Python进阶者
2年前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这