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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
lecepin4 分钟前
AI Coding 资讯 2025-09-10
前端·javascript·面试
Petrichoe2 小时前
通过@Transactional常见的失效场景带你通俗理解SpringAOP的原理
面试
a_blue_ice2 小时前
JAVA 面试 MySQL
java·mysql·面试
前端小巷子2 小时前
JS 实现图片瀑布流布局
前端·javascript·面试
月阳羊3 小时前
【硬件-笔试面试题-76】硬件/电子工程师,笔试面试题(知识点:H桥驱动电路的设计要点)
java·单片机·嵌入式硬件·面试·职场和发展
Hilaku4 小时前
面试官开始问我AI了,前端的危机真的来了吗?
前端·javascript·面试
在未来等你5 小时前
Elasticsearch面试精讲 Day 15:索引别名与零停机更新
大数据·分布式·elasticsearch·搜索引擎·面试
2301_781668615 小时前
Redis 面试
java·redis·面试
程序新视界6 小时前
在职场,尽量不要成为这样的“人才”
面试·求职
小奋斗6 小时前
以Chrome 为代表的浏览器架构详解
面试·程序员