Closest Nodes Queries in a Binary Search Tree — LeetCode 2476 Python Solution
- Problem
- #2476
- Pattern
- Monotonic Stack
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are given the root of a binary search tree and an array queries of size n consisting of positive integers. Find a 2D array answer of size n where answer[i] = [mini, maxi]: mini is the largest value in the tree that is smaller than or equal to queries[i].
Example
- Input
- root = [6,2,13,1,4,9,15,null,null,null,null,null,null,14], queries = [2,5,16]
- Output
- [[2,2],[4,6],[15,-1]]
- Explanation
- We answer the queries in the following way:
Python solution
# 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(root: Optional[TreeNode]):
if root is None:
return
dfs(root.left)
nums.append(root.val)
dfs(root.right)
nums = []
dfs(root)
ans = []
for x in queries:
i = bisect_left(nums, x + 1) - 1
j = bisect_left(nums, x)
mi = nums[i] if 0 <= i < len(nums) else -1
mx = nums[j] if 0 <= j < len(nums) else -1
ans.append([mi, mx])
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n + m \times \log n) |
| Space | O(n) auxiliary |
Pattern: Monotonic Stack
Answer "what is the next greater element" for every position in one pass. LeetCode 2476. Closest Nodes Queries in a Binary Search Tree is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The monotonic stack guide has the Python template for the pattern and the 225 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2476. Closest Nodes Queries in a Binary Search Tree?
- LeetCode 2476. Closest Nodes Queries in a Binary Search Tree is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2476. Closest Nodes Queries in a Binary Search Tree?
- The Python solution on this page runs in O(n + m \times \log n).
- What is the space complexity of LeetCode 2476. Closest Nodes Queries in a Binary Search Tree?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2476. Closest Nodes Queries in a Binary Search Tree cover?
- LeetCode 2476. Closest Nodes Queries in a Binary Search Tree is tagged Tree, Depth-First Search, Binary Search Tree, Array, Binary Search and Binary Tree on LeetCode.