字节面试手撕中等题但还没做出来

题目是,二叉树最大的宽度!这个做过,但因为不是hot100 ,我就是做了一遍就过去了。结果今天手撕这道题。。。

刚刚试了下,超时了!好的办法是,把节点和下标(假设是满二叉树),就能解决了。

面试写的代码

python 复制代码
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def widthOfBinaryTree(self, root: Optional[TreeNode]) -> int:
        res = 0
        q = []
        q.append(root)
        res = max(res, len(q))
        while True:
            #res =max(res,n)# 判断这一层的宽度
            for i in range(len(q)):
                curr = q.pop(0)
                if not curr:
                    q.append(None)
                    q.append(None)
                elif not curr.left and curr.right:
                    q.append(None)
                    q.append(curr.right)
                elif curr.left and not curr.right:
                    q.append(curr.left)
                    q.append(None)
                else:
                    q.append(curr.left)
                    q.append(curr.right)
            if len(q) == 0:
                return res
            while q and not q[0]:
                q.pop(0)
            while q and not q[-1]:
                q.pop()

            res = max(res, len(q))
相关推荐
ShineWinsu28 分钟前
对于Qt:QFontDialog的解析
c++·qt·面试·gui·字体·客户端·qfontdialog
某哈压力大4 小时前
Vue的双向绑定与自定义组件的v-model
前端·面试
怕浪猫4 小时前
GLM-5.4 深度拆解:750B 参数如何「循环」出 2-3T 级智能?
算法·面试·github
CoderYanger5 小时前
Java EE 进阶:11. SpringBoot 统一功能处理(第二弹):DispatcherServlet 源码分析+适配器模式
java·数据库·hive·spring boot·面试·java-ee·mybatis
Moment7 小时前
27B 的本地模型也能做知识图谱?太强了!😍😍😍
前端·后端·面试
我叫黑大帅19 小时前
换尺寸、转个角度就认不出同一张图?让 16×16 灰度网格做感知去重
后端·面试·php
Moment1 天前
AI 写代码越来越快,程序员为什么反而更累了
前端·后端·面试
CoderYanger1 天前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
JianZhen✓1 天前
后端进阶 13 问:CI/CD、Prisma、ORM、ER 图、SSE、索引事务、Nest 生命周期一次讲透(附面试答法)
ci/cd·面试·职场和发展
利威尔xu1 天前
2026-11-19-Go反射为什么慢面试
开发语言·面试·golang