题解 | #牛牛的二叉树问题#
牛牛的二叉树问题
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])