272. Closest Binary Search Tree Value II
HardSolutions in Python, Java, C++, TypeScript
Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.
Approach
The problem asks us to find k values in a Binary Search Tree (BST) that are closest to a given target. The key property of a BST is that an in-order traversal of its nodes results in a sorted sequence of values. This suggests that the k closest values will likely be clustered around the target in this sorted sequence.
Solution
Closest Binary Search Tree Value II in Python
# 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 closestKValues(self, root: Optional[TreeNode], target: float, k: int) -> List[int]:
predecessors = []
successors = []
# Initialize the stacks. `predecessors` will hold the path to the largest node
# with value <= target. `successors` will hold the path to the smallest node
# with value > target.
curr = root
while curr:
if curr.val <= target:
predecessors.append(curr)
curr = curr.right
else:
successors.append(curr)
curr = curr.left
# Helper to get predecessor and update stack
def get_predecessor():
node = predecessors.pop()
val = node.val
# Next predecessor is the rightmost node in the left subtree
curr = node.left
while curr:
predecessors.append(curr)
curr = curr.right
return val
# Helper to get successor and update stack
def get_successor():
node = successors.pop()
val = node.val
# Next successor is the leftmost node in the right subtree
curr = node.right
while curr:
successors.append(curr)
curr = curr.left
return val
result = []
# Collect k values by picking the closer one from the tops of the two stacks
for _ in range(k):
if not successors:
result.append(get_predecessor())
elif not predecessors:
result.append(get_successor())
else:
pred_diff = target - predecessors[-1].val
succ_diff = successors[-1].val - target
if pred_diff < succ_diff:
result.append(get_predecessor())
else:
result.append(get_successor())
return result
Closest Binary Search Tree Value II in Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
import java.util.Stack;
import java.util.List;
import java.util.ArrayList;
class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
List<Integer> result = new ArrayList<>();
// Use Deque as a stack for better performance, but Stack is fine too.
Stack<TreeNode> predecessors = new Stack<>();
Stack<TreeNode> successors = new Stack<>();
// Initialize both stacks by traversing the tree.
// Predecessors stack will contain the path to the largest node <= target.
// Successors stack will contain the path to the smallest node > target.
TreeNode curr = root;
while (curr != null) {
if (curr.val <= target) {
predecessors.push(curr);
curr = curr.right;
} else {
successors.push(curr);
curr = curr.left;
}
}
// Collect k closest values by comparing the tops of the two stacks.
for (int i = 0; i < k; i++) {
if (successors.isEmpty()) {
result.add(getPredecessor(predecessors));
} else if (predecessors.isEmpty()) {
result.add(getSuccessor(successors));
} else {
double predDiff = target - predecessors.peek().val;
double succDiff = successors.peek().val - target;
if (predDiff < succDiff) {
result.add(getPredecessor(predecessors));
} else {
result.add(getSuccessor(successors));
}
}
}
return result;
}
// Helper function to get the current predecessor value and update the stack to the next one.
private int getPredecessor(Stack<TreeNode> st) {
TreeNode node = st.pop();
int val = node.val;
// The next predecessor is the rightmost node in the left subtree.
TreeNode curr = node.left;
while (curr != null) {
st.push(curr);
curr = curr.right;
}
return val;
}
// Helper function to get the current successor value and update the stack to the next one.
private int getSuccessor(Stack<TreeNode> st) {
TreeNode node = st.pop();
int val = node.val;
// The next successor is the leftmost node in the right subtree.
TreeNode curr = node.right;
while (curr != null) {
st.push(curr);
curr = curr.left;
}
return val;
}
}
Closest Binary Search Tree Value II in C++
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
#include <stack>
#include <vector>
#include <cmath>
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
vector<int> result;
stack<TreeNode*> predecessors;
stack<TreeNode*> successors;
// Initialize both stacks
TreeNode* curr = root;
while (curr != nullptr) {
if (curr->val <= target) {
predecessors.push(curr);
curr = curr->right;
} else {
successors.push(curr);
curr = curr->left;
}
}
// Collect k closest values
for (int i = 0; i < k; ++i) {
if (successors.empty()) {
result.push_back(getPredecessor(predecessors));
} else if (predecessors.empty()) {
result.push_back(getSuccessor(successors));
} else {
double pred_diff = target - predecessors.top()->val;
double succ_diff = successors.top()->val - target;
if (pred_diff < succ_diff) {
result.push_back(getPredecessor(predecessors));
} else {
result.push_back(getSuccessor(successors));
}
}
}
return result;
}
private:
// Helper function to get the current predecessor value and update the stack
int getPredecessor(stack<TreeNode*>& st) {
TreeNode* node = st.top();
st.pop();
int val = node->val;
// Find the next inorder predecessor
TreeNode* curr = node->left;
while (curr != nullptr) {
st.push(curr);
curr = curr->right;
}
return val;
}
// Helper function to get the current successor value and update the stack
int getSuccessor(stack<TreeNode*>& st) {
TreeNode* node = st.top();
st.pop();
int val = node->val;
// Find the next inorder successor
TreeNode* curr = node->right;
while (curr != nullptr) {
st.push(curr);
curr = curr->left;
}
return val;
}
};
Closest Binary Search Tree Value II in TypeScript
/**
* Definition for a binary tree node.
* class TreeNode {
* val: number
* left: TreeNode | null
* right: TreeNode | null
* constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
* }
*/
function closestKValues(root: TreeNode | null, target: number, k: number): number[] {
if (!root) {
return [];
}
const predecessors: TreeNode[] = [];
const successors: TreeNode[] = [];
// Initialize both stacks
let curr: TreeNode | null = root;
while (curr) {
if (curr.val <= target) {
predecessors.push(curr);
curr = curr.right;
} else {
successors.push(curr);
curr = curr.left;
}
}
// Helper to get predecessor and update stack
const getPredecessor = (): number => {
const node = predecessors.pop()!;
const val = node.val;
let p: TreeNode | null = node.left;
while (p) {
predecessors.push(p);
p = p.right;
}
return val;
};
// Helper to get successor and update stack
const getSuccessor = (): number => {
const node = successors.pop()!;
const val = node.val;
let s: TreeNode | null = node.right;
while (s) {
successors.push(s);
s = s.left;
}
return val;
};
const result: number[] = [];
for (let i = 0; i < k; i++) {
if (successors.length === 0) {
result.push(getPredecessor());
} else if (predecessors.length === 0) {
result.push(getSuccessor());
} else {
const predDiff = target - predecessors[predecessors.length - 1].val;
const succDiff = successors[successors.length - 1].val - target;
if (predDiff < succDiff) {
result.push(getPredecessor());
} else {
result.push(getSuccessor());
}
}
}
return result;
}
More Hard LeetCode answers
Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.
LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.