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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
xuxigifxfh16 分钟前
面试记录2026
java·mysql·面试·职场和发展
丑陋小蚊子23 分钟前
校招没有实习,社团活动和课程项目先写哪个?
面试·求职招聘·大学生·简历·简历下载
Rain的Java大神之路2 小时前
Java PDF导出,90%的人选错库!11个生产坑+选型+代码,一次讲透
java·后端·面试
怕浪猫3 小时前
AI Agent 的安全怎么保障?面试最后一关的终极问题
算法·面试·github
Interview Aid11213 小时前
SoFi 面试流程全解析:技术面试、OA 与备考指南
面试·职场和发展
YangYang9YangYan14 小时前
2027数学与应用数学转产品经理:面试解释与项目准备
面试·职场和发展·产品经理
YangYang9YangYan17 小时前
2027 届秋招求职|金融科技背景,反欺诈岗位面试案例题考点拆解
科技·面试·金融
积跬步以至千里17 小时前
Agent 工程师学习线路 — 核心知识点总结
面试
Zelman21 小时前
测试层级与测试类型
后端·面试·测试
考研保研资料分享1 天前
自动化控制保研经验合辑:上交夏令营、北工大预推免与跨专业面试复盘(2025)
运维·面试·自动化