Similar Problems
Similar Problems not available
Closest Nodes Queries In A Binary Search Tree - Leetcode Solution
Companies:
LeetCode: Closest Nodes Queries In A Binary Search Tree Leetcode Solution
Difficulty: Medium
Topics: binary-search-tree binary-search depth-first-search tree binary-tree array
Problem statement: Given a binary search tree (BST) and a target node k, find the two closest nodes to k in the BST.
Solution: We can solve this problem using iterative or recursive approach. However, in this solution, I will explain the iterative approach.
We will traverse the BST in inorder and maintain a queue of size 2 with the closest nodes seen so far. Let's call this queue closestNodes
.
Algorithm:
- Initialize a variable
curr
to the root of the BST. - Initialize an empty queue
closestNodes
. - While
curr
is not null orclosestNodes
is not empty: a. Ifcurr
is not null, pushcurr
onto a stack and updatecurr
to its left child. b. Ifcurr
is null, pop an elementnode
from the stack and: i. IfclosestNodes
is empty, pushnode
ontoclosestNodes
. ii. Ifnode
is closer to the target than the first element inclosestNodes
, insertnode
at the front ofclosestNodes
. iii. Else ifnode
is closer to the target than the second element inclosestNodes
, insertnode
at the second position inclosestNodes
. iv. If the size ofclosestNodes
is greater than 2, remove the last element fromclosestNodes
. v. Updatecurr
tonode
's right child. - Return the two elements in
closestNodes
.
Let's analyze the time and space complexity of this algorithm. Time complexity is O(h+k), where h is the height of the BST and k is the number of closest nodes we want to find. Space complexity depends on the size of the stack used for inorder traversal and is O(h).
Here's the implementation of the above algorithm:
public List<Integer> closestNodes(TreeNode root, double target) {
Stack<TreeNode> stack = new Stack<>();
List<Integer> closestNodes = new ArrayList<>();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
TreeNode node = stack.pop();
if (closestNodes.isEmpty()) {
closestNodes.add(node.val);
} else if (Math.abs(node.val - target) < Math.abs(closestNodes.get(0) - target)) {
closestNodes.add(0, node.val);
} else if (closestNodes.size() < 2 || Math.abs(node.val - target) < Math.abs(closestNodes.get(1) - target)) {
closestNodes.add(1, node.val);
}
if (closestNodes.size() > 2) {
closestNodes.remove(2);
}
curr = node.right;
}
return closestNodes;
}
Note: This solution assumes that the input BST does not have any duplicates. If duplicates exist, we need to modify the condition on lines 10-12 to ensure that we don't add the same value to closestNodes
.
Closest Nodes Queries In A Binary Search Tree Solution Code
1