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

题目是,二叉树最大的宽度!这个做过,但因为不是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))
相关推荐
岁岁种桃花儿34 分钟前
SpringCloud超高质量面试高频题300道题
spring·spring cloud·面试
努力学算法的蒟蒻1 小时前
day75(2.3)——leetcode面试经典150
面试·职场和发展
南风知我意9571 小时前
【前端面试3】初中级难度
前端·javascript·面试
华清远见成都中心1 小时前
GPIO(通用输入输出)面试中高频问题
单片机·面试·职场和发展
蒹葭玉树7 小时前
【C++上岸】C++常见面试题目--操作系统篇(第三十期)
c++·面试·risc-v
cyforkk7 小时前
16、Java 基础硬核复习:网络编程的核心逻辑与面试考点
java·网络·面试
Bella的成长园地18 小时前
面试中关于 c++ async 的高频面试问题有哪些?
c++·面试
Abona19 小时前
C语言嵌入式全栈Demo
linux·c语言·面试
她说..1 天前
策略模式+工厂模式实现审批流(面试问答版)
java·后端·spring·面试·springboot·策略模式·javaee
七禾页丫1 天前
面试记录14 上位机软件工程师
面试·职场和发展