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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
熬了夜的程序员25 分钟前
【华为机试】34. 在排序数组中查找元素的第一个和最后一个位置
数据结构·算法·华为od·华为·面试·golang
小徐不徐说2 小时前
C++ 模板与 STL 基础入门:从泛型编程到实战工具集
开发语言·数据结构·c++·qt·面试
牛客企业服务6 小时前
2025校招AI应用:校园招聘的革新与挑战
大数据·人工智能·机器学习·面试·职场和发展·求职招聘·语音识别
倔强青铜三6 小时前
苦练Python第38天:input() 高级处理,安全与异常管理
人工智能·python·面试
小高0076 小时前
🚀把 async/await 拆成 4 块乐高!面试官当场鼓掌👏
前端·javascript·面试
雲墨款哥6 小时前
为什么我的this.name输出了空字符串?严格模式与作用域链的微妙关系
前端·javascript·面试
丘山子8 小时前
DNS 原理入门
前端·后端·面试
丘山子11 小时前
Python 布尔运算的优雅实践
后端·python·面试
海风极客12 小时前
Go内存逃逸分析,真的很神奇吗?
后端·面试