272 Closest Binary Search Tree Value II
272. Closest Binary Search Tree Value II
1. Question
2. Implementation
class Solution {
public List<Integer> closestKValues(TreeNode root, double target, int k) {
LinkedList<Integer> res = new LinkedList<>();
if (root == null) {
return res;
}
Stack<TreeNode> stack = new Stack<>();
TreeNode curNode = root;
while (curNode != null || !stack.isEmpty()) {
if (curNode != null) {
stack.push(curNode);
curNode = curNode.left;
}
else {
curNode = stack.pop();
if (res.size() < k) {
res.add(curNode.val);
}
else if (Math.abs(curNode.val - target) < Math.abs(res.getFirst() - target)) {
res.removeFirst();
res.add(curNode.val);
}
curNode = curNode.right;
}
}
return res;
}
}3. Time & Space Complexity
Last updated