求一颗二叉树的宽度

简介: 求一颗二叉树的宽度

前言

如何完成二叉树的宽度优先遍历(常见题目:求一颗二叉树的宽度)

二叉树的宽度优先遍历

以下面的二叉树为例:


image.png


如果对其进行宽度优先遍历,打印出来的顺序是1,2,3,4,5,6,7

Java版

public static void w(Node head){
    if(head == null){
        return;
    }
    Queue<Node> queue = new LinkedList<>();
    queue.add(head);
    while(!queue.isEmpty()){
        Node cur = queue.poll();
        System.out.printIn(cur.value);
        if(cur.left != null){
            queue.add(cur.left);
        }
        if(cur.right != null){
            queue.add(cur.right);
        }
    }
}
复制代码

求一颗二叉树的宽度

题目分析

以下面的二叉树为例:

网络异常,图片无法展示
|

这个二叉树的最大宽度是3,位于第三层。

在上述对二叉树的宽度优先遍历的基础上,我们还需要在遍历时知道该节点位于第几层,以便于记录每一层中的节点个数。

public static void w(Node head){
    if(head == null){
        return;
    }
    Queue<Node> queue = new LinkedList<>();
    queue.add(head);
    HashMap<Node, Integer> levelMap = new HashMap<>();
    levelMap.put(head, 1);
    int curLevel = 1;
    int curLevelNodes = 0;
    int max = Integer.MIN_VALUE;
    while(!queue.isEmpty()){
        Node cur = queue.poll();
        int curNodeLevel = levelMap.get(cur);
        if(curNodeLevel == curLevel){
            curLevelNodes++;
        }else{
            curLevel++;
            curLevelNodes=1;
        }
        max = Math.max(max, curLevelNodes);
        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);
        }
    }
    return max
}
复制代码

进阶:Leetcode- 662. 二叉树最大宽度

根据上面的例子,这道题好像也是广度优先遍历的一个例子,在其广度优先遍历的基础上,遍历时知道该节点位于哪一层,并记录该层的节点个数,但是好像,此法不通...因为它中间空的位置也要计算!

难点:两端点之间的null节点也计入长度

此时,我们可以利用完全二叉树的性质:

  • 对于一颗完全二插树,如果按照从上至下,从左往右对所有节点从零开始顺序编号
  • 则父节点的左孩子节点的序号:2i+1
  • 父节点的左孩子节点的序号:2i+2
var widthOfBinaryTree = function(root) {
    // 首先实现广度优先遍历,在其基础上,遍历时知道该节点位于哪一层,并记录该层的节点个数
    // 难点:两端点之间的null节点也计入长度
    // const queue = [root];
    // while(queue.length){
    //     const cur = queue.shift();
    //     console.log(cur.val);
    //     cur.left && queue.push(cur.left);
    //     cur.right && queue.push(cur.right);
    // }
    // 如果两端点之间的null节点不计入长度
    // const queue = [root];
    // const levelMap = new Map();
    // let curLevel = 1;
    // let max = 0;
    // let curLevelNodes = 0;
    // levelMap.set(root, 1);
    // while(queue.length>0){
    //     const cur = queue.shift();
    //     const curNodeLevel = levelMap.get(cur);
    //     if(curNodeLevel === curLevel){
    //         curLevelNodes++;
    //     }else{
    //         curLevel++;
    //         curLevelNodes = 1;
    //     }
    //     max = Math.max(max, curLevelNodes);
    //     if(cur.left){
    //         queue.push(cur.left);
    //         levelMap.set(cur.left, curNodeLevel+1);
    //     }
    //     if(cur.right){
    //         queue.push(cur.right);
    //         levelMap.set(cur.right, curNodeLevel+1)
    //     }
    //     console.log(cur, curNodeLevel, curLevel, curLevelNodes, max) ;
    // }
    // return max
    const max = [];
    function dfs(node, dep, idx) {
        if (!node) return;
        max[dep] = (max[dep] || [idx, idx]);
        max[dep][0] = Math.min(max[dep][0], idx);
        max[dep][1] = Math.max(max[dep][1], idx);
        dfs(node.left, dep + 1, (idx << 1) + 1);
        dfs(node.right, dep + 1, (idx << 1) + 2);
    }
    dfs(root, 0, 0);
    return max.reduce((max, [l, r]) => Math.max(max, r - l), 0) + 1;
};



相关文章
|
算法 Java
折半查找算法[二分查找法]算法的实现和解决整数溢出问题~
折半查找算法[二分查找法]算法的实现和解决整数溢出问题~
260 1
|
存储 算法 程序员
迪杰斯特拉(Dijkstra)算法(C/C++)
迪杰斯特拉(Dijkstra)算法(C/C++)
|
JavaScript API 开发者
掌握ArkTS,打造HarmonyOS应用新视界:从“Hello World”到状态管理,揭秘鸿蒙UI开发的高效秘诀
【10月更文挑战第19天】ArkTS(ArkUI TypeScript)是华为鸿蒙系统中用于开发用户界面的声明式编程语言,结合了TypeScript和HarmonyOS的UI框架。本文介绍ArkTS的基本语法,包括组件结构、模板和脚本部分,并通过“Hello World”和计数器示例展示其使用方法。
697 1
|
关系型数据库 定位技术 Python
geopandas中拓扑错误的发现诊断与修复
geopandas中拓扑错误的发现诊断与修复
425 6
|
存储 云计算 虚拟化
什么是云计算
云计算通过租用远程服务器,为用户提供可无限扩展、按需使用的计算服务与数据存储,无需自建服务器。其特点包括虚拟化技术、动态可扩展、按需部署、高灵活性和可靠性、高性价比及可扩展性。根据不同需求,云计算服务可分为IaaS、PaaS和SaaS三种类型,共同构成云计算堆栈。
1077 3
|
安全 网络协议 网络安全
在实现HTTPS时,有哪些常见的安全协议
在实现HTTPS时,有哪些常见的安全协议
723 1
|
网络安全 开发工具 git
【git】解决git报错:ssh:connect to host github.com port 22: Connection timed out 亲测有效
【git】解决git报错:ssh:connect to host github.com port 22: Connection timed out 亲测有效
5592 1
|
前端开发 API PHP
分享75个PHP源码,总有一款适合您
分享75个PHP源码,总有一款适合您
548 2
|
JavaScript 前端开发 关系型数据库
Django+Vue快速实现博客网站
Django是一个开放源代码的Web应用框架,由Python写成。采用了MTV的框架模式,即模型M,视图V和模版T。它最初是被开发来用于管理劳伦斯出版集团旗下的一些以新闻内容为主的网站的,即是CMS(内容管理系统)软件。对于博客网站来说是典型的CMS应用。本文介绍通过Django+Vue的博客模版快速实现一个可用的博客网站。
381 1
|
SQL 分布式计算 Spark
Spark【Spark SQL(四)UDF函数和UDAF函数】
Spark【Spark SQL(四)UDF函数和UDAF函数】

热门文章

最新文章