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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
liang_jy42 分钟前
Android 事件分发机制(一)—— 全流程源码解析
android·面试·源码
Dream it possible!3 小时前
LeetCode 面试经典 150_分治_将有序数组转换为二叉搜索树(105_108_C++_简单)(递归)
c++·leetcode·面试
鱼鱼块3 小时前
告别重复传参!用柯里化提升代码优雅度
前端·javascript·面试
风止何安啊3 小时前
那些让你 debug 到凌晨的陷阱,我帮你踩平了:React Hooks 避坑指南
前端·react.js·面试
a程序小傲3 小时前
得物Java面试被问:Fork/Join框架的使用场景
java·开发语言·面试
阿蒙Amon3 小时前
C#每日面试题-简述可空类型
microsoft·面试·c#
阿拉伯柠檬4 小时前
传输层与传输层协议UDP
linux·网络·网络协议·面试·udp
得贤招聘官5 小时前
破局传统招聘:AI面试智能体构建精准高效新生态
大数据·人工智能·面试
南山安14 小时前
JavaScript 函数柯里化:从入门到实战,一文搞定(面试可用)
javascript·面试·函数式编程