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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
夕除3 小时前
Redis 过期策略
redis·笔记·面试
时间的拾荒人6 小时前
CMake 常用命令详解:从版本声明到安装部署
c++·面试
香蕉大香蕉(06敬畏市场)13 小时前
MySQL 单点详解(03)
java·数据库·mysql·面试·八股·大厂实习
道尔柯南15 小时前
C++ 内存管理详解:从 malloc/free 到 new/delete
c++·面试
CoderYanger15 小时前
Java EE 进阶:5. Spring IoC&DI(第三弹):Spring DI
java·开发语言·spring boot·spring·面试·java-ee·mvc
八月的雨季 最後的冰吻17 小时前
音视频面试--延迟优化
面试·职场和发展·音视频
ShineWinsu17 小时前
对于Qt:QLabel常见属性的解析
c++·qt·面试·笔试·gui·标签·qlabel
weixin_3077791318 小时前
RAG 级联失效分析——面试中的错误归因艺术
人工智能·python·面试·职场和发展
每天进步一点点km1 天前
自用-牛客网-华为机试编程模拟题1-python
华为od·华为·面试
frjc2 天前
分布式服务拆分实战指南:从底层逻辑到面试话术
微服务·面试·职场和发展