Leetcode 2476: Closest Nodes Queries in a Binary Search Tree

grid47
grid47
Exploring patterns and algorithms
Mar 4, 2024 7 min read

You are given the root of a binary search tree (BST) and an array of queries. For each query, find the largest value smaller than or equal to the query value and the smallest value greater than or equal to the query value in the tree.
Problem
Approach
Steps
Complexity
Input: You are given the root of a binary search tree (BST) and an array of queries.
Example: root = [10, 5, 20, 2, 7, 15, 30], queries = [6, 25, 5]
Constraints:
• The number of nodes in the tree is between 2 and 10^5.
• 1 <= Node.val <= 10^6
• The length of queries is between 1 and 10^5.
• 1 <= queries[i] <= 10^6
Output: Return a 2D array where each element represents the answers to each query. The first element in the pair should be the largest value smaller than or equal to the query, and the second should be the smallest value greater than or equal to the query.
Example: Output: [[5, 7], [20, 20], [5, 5]]
Constraints:
• The output should be a 2D array of integers.
Goal: For each query, find the largest value smaller than or equal to the query and the smallest value greater than or equal to the query.
Steps:
• Traverse the binary search tree (BST) and store the values in a sorted order.
• For each query, find the largest number less than or equal to the query and the smallest number greater than or equal to the query using binary search techniques.
Goal: The problem's constraints ensure that the number of nodes and queries are within reasonable bounds for efficient computation.
Steps:
• The number of nodes in the BST is between 2 and 10^5.
• The length of the queries array is between 1 and 10^5.
• Each query value is between 1 and 10^6.
Assumptions:
• The binary search tree (BST) is a valid BST, and the input query array contains positive integers.
Input: Input: root = [10,5,20,2,7,15,30], queries = [6, 25, 5]
Explanation: For the query 6, the largest number smaller or equal to 6 is 5, and the smallest number greater or equal to 6 is 7. For the query 25, the largest number smaller or equal to 25 is 20, and the smallest number greater or equal to 25 is 20. For the query 5, the largest number smaller or equal to 5 is 5, and the smallest number greater or equal to 5 is 5.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus