栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【Leetcode二叉树】662. 二叉树最大宽度(利用父子节点pos关系求宽度,非常好的思路)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【Leetcode二叉树】662. 二叉树最大宽度(利用父子节点pos关系求宽度,非常好的思路)

文章目录
    • Leetcode662
      • 1.问题描述
      • 2.解决方案
        • 整体思路:
        • 解法一:用beginPos维护pos进而求宽度
        • 解法二:用ArrayList维护pos进而求宽度

Leetcode662 1.问题描述



2.解决方案 整体思路:

1.这个给每个节点一个pos值,进而封装一层的思想非常优秀
2.既能使用到pos值,又不用使用静态数组存储节点
3.即为左右指针存储树,还能使用到静态数组的特性


解法一:用beginPos维护pos进而求宽度

1.思路就是每一层的第一个节点为beginPos,后面的节点都减去beginPos,最后求最大值
2.但是leetcode有一个样例没过

class AnnotatedNode {
    TreeNode node;
    int pos;
    AnnotatedNode(TreeNode n,int p) {
        node = n;
        pos = p;
    }
}

public class lc662 {
    public int widthOfBinaryTree(TreeNode root) {
        Queue queue = new linkedList<>();
        queue.add(new AnnotatedNode(root,0));
        int max=0;
        while(queue.isEmpty()==false){
            int beginPos=Integer.MAX_VALUE;
            int len=queue.size();
            for(int i=0;i 



解法二:用ArrayList维护pos进而求宽度

1.思路就是把每一层不为空的节点的pos加入数组中
2.最后只要看数组首尾之差就是宽度了

class AnnotatedNode {
    TreeNode node;
    int pos;
    AnnotatedNode(TreeNode n,int p) {
        node = n;
        pos = p;
    }
}

public class lc662 {
    public int widthOfBinaryTree1(TreeNode root) {
        Queue queue = new linkedList<>();
        queue.add(new AnnotatedNode(root,0));
        int max=0;
        while(queue.isEmpty()==false){
            int len=queue.size();
            ArrayList posList = new ArrayList<>();
            for(int i=0;i
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/630741.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号