{}
run-icon
main.py
# 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 closestNodes(self, root: Optional[TreeNode], queries: List[int]) -> List[List[int]]: def DFS(node, data): if not node: return None DFS(node.left, data) data.append(node.val) DFS(node.right, data) data = [] DFS(root, data) n = len(data) def calc(val): index = bisect.bisect_left(data, val) if index == n: return data[-1], -1 if data[index] == val: return [val, val] if index == 0: return [-1, data[0]] return [data[index-1], data[index]] return [calc(val) for val in queries]
Output