题解 | #牛牛的二叉树问题#

牛牛的二叉树问题

https://www.nowcoder.com/practice/1b80046da95841a9b648b10f1106b04e

from heapq import heappush, heappop

#优先队列
class Solution:
    def findClosestElements(self, root: TreeNode, target: float, m: int) -> List[int]:
        # write code here

        heap, nodes = [], [root]
        while nodes:
            nodes, temps = [], nodes
            for node in temps:
                if len(heap) < m:
                    heappush(heap, (-abs(node.val - target), node.val))
                else:
                    if abs(node.val - target) < abs(heap[0][0]):
                        heappop(heap)
                        heappush(heap, (-abs(node.val - target), node.val))

                if node.left is not None:
                    nodes.append(node.left)
                if node.right is not None:
                    nodes.append(node.right)

        return sorted([node for _, node in heap])

全部评论

相关推荐

2024-11-19 23:36
未填写教育信息 Java
废铁汽车人:秋招真是牛鬼蛇神齐聚一堂
点赞 评论 收藏
分享
三斤大芒果:切图仔过年回去天塌了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务