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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
圣殿骑士-Khtangc19 分钟前
Go-Map面试核心考点从哈希冲突到并发安全的完整解析
面试·golang·哈希算法
码匠许师傅1 小时前
【C++ 面试真题】聊聊 volatile 和 mutable
开发语言·c++·面试
黄敬峰2 小时前
Harness 工程:用 LLM 当评委,自动生成、评测、择优一条龙
面试
ocean21033 小时前
八股刷题之:变体树
面试·面试题·面试真题·变体树·八股精·深度拓展·高效刷题
何时梦醒3 小时前
第三篇:React 组件化开发 — 函数即组件的哲学与实践
react.js·面试·typescript
胡萝卜术3 小时前
编译期与运行期的双重防线:从 TypeScript 类型之争到 LLM 输出的自动化择优
前端·设计模式·面试
用户852495071843 小时前
Harness 工程:用工程化手段驾驭 LLM,而不是迷信一次回答
面试
Dr.kangder3 小时前
嵌入式面试总结(一)——嵌入式系统实时性
面试·职场和发展·架构·嵌入式·虚拟化
何时梦醒4 小时前
TypeScript 类型系统核心:type 与 interface 全方位深度对比(附实战案例)
前端·面试·typescript
书源4 小时前
AI 能写代码之后,前端工程师的价值在哪里?
前端·面试·程序员