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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
不简说1 小时前
JS 代码技巧 vol.1 — 10 个让代码少写 30% 的小套路
前端·javascript·面试
Mr_凌宇1 小时前
# AI 应用工程入门学习笔记 一
人工智能·面试·程序员
Mr_凌宇2 小时前
AI 应用工程进阶扩展学习笔记 二
前端·面试
Hyyy2 小时前
Git Worktree 完全讲解
前端·后端·面试
云技纵横3 小时前
Redis 延迟双删还是读到脏数据?一次缓存一致性事故
redis·后端·面试
weedsfly3 小时前
前端开发中的代理模式——从 Vue 3 响应式到日常开发
前端·javascript·面试
咖啡八杯3 小时前
GoF设计模式——状态模式
java·面试·架构
尘世中一位迷途小书童4 小时前
Cesium 涟漪扩散点:自定义材质,参数调对了才好看
前端·面试
zzz_23684 小时前
【Java实习面试算法冲刺】图论
java·算法·面试
Sam_Deep_Thinking5 小时前
一次线程池线上故障复盘:四层防线如何避免数据丢失
java·面试·程序员