优选算法-队列+宽搜(BFS):72.二叉树的最大宽度

题目链接:662. 二叉树最大宽度(中等)

算法原理:

解法一:硬来(超时)

解法二:利用数组存储二叉树的方式,给节点编号

击败4.01%

时间复杂度O(N)

Java代码:

java 复制代码
/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 王洋
 * Date: 2025-09-17
 * Time: 14:09
 */

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.List;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    //662. 二叉树最大宽度
    //IDEA没有内置Pair,需要自己实现
    class Pair<K,V>{
        private K key;
        private V value;
        public Pair(K key,V value){
            this.key=key;
            this.value=value;
        }
        public K getKey(){
            return key;
        }
        public V getValue(){
            return value;
        }
    }
    public int widthOfBinaryTree(TreeNode root) {
        if(root==null) return 0;
        List<Pair<TreeNode,Integer>> q=new ArrayList<>();
        //Pair<TreeNode,Integer>这一整体类似数据类型
        q.add(new Pair<TreeNode,Integer>(root,1));int ret=0;
        while(!q.isEmpty()){
            //更新宽度
            Pair<TreeNode,Integer> left=q.get(0);
            Pair<TreeNode,Integer> right=q.get(q.size()-1);
            ret=Math.max(ret,right.getValue()-left.getValue()+1);

            List<Pair<TreeNode,Integer>> tmp=new ArrayList<>();
            for(Pair<TreeNode,Integer> t:q){//从当前层取出每个对
                TreeNode node=t.getKey();
                int index=t.getValue();
                if(node.left!=null)
                    tmp.add(new Pair<TreeNode,Integer>(node.left,2*index));
                if(node.right!=null)
                    tmp.add(new Pair<TreeNode,Integer>(node.right,2*index+1));
            }
            q=tmp;//覆盖
        }
        return ret;
    }
}
相关推荐
dapeng28701 小时前
分布式系统容错设计
开发语言·c++·算法
qq_417695051 小时前
代码热修复技术
开发语言·c++·算法
badhope6 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园7 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
C++ 老炮儿的技术栈7 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl7 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
大阿明7 小时前
Spring Boot(快速上手)
java·spring boot·后端
Liu628887 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
bearpping8 小时前
Java进阶,时间与日期,包装类,正则表达式
java
IT猿手8 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队