优选算法-队列+宽搜(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;
    }
}
相关推荐
皮皮林5511 小时前
Java性能调优黑科技!1行代码实现毫秒级耗时追踪,效率飙升300%!
java
冰_河1 小时前
QPS从300到3100:我靠一行代码让接口性能暴涨10倍,系统性能原地起飞!!
java·后端·性能优化
地平线开发者2 小时前
SparseDrive 模型导出与性能优化实战
算法·自动驾驶
董董灿是个攻城狮2 小时前
大模型连载2:初步认识 tokenizer 的过程
算法
地平线开发者3 小时前
地平线 VP 接口工程实践(一):hbVPRoiResize 接口功能、使用约束与典型问题总结
算法·自动驾驶
罗西的思考3 小时前
AI Agent框架探秘:拆解 OpenHands(10)--- Runtime
人工智能·算法·机器学习
桦说编程4 小时前
从 ForkJoinPool 的 Compensate 看并发框架的线程补偿思想
java·后端·源码阅读
躺平大鹅6 小时前
Java面向对象入门(类与对象,新手秒懂)
java
HXhlx6 小时前
CART决策树基本原理
算法·机器学习