# [LeetCode282]Closest Binary Search Tree Value II

``````Given a non-empty binary search tree and a target value, find k values in the BST that are closest to the target.

Note:
Given target value is a floating point.
You may assume k is always valid, that is: k ≤ total nodes.
You are guaranteed to have only one unique set of k values in the BST that are closest to the target.
Assume that the BST is balanced, could you solve it in less than O(n) runtime (where n = total nodes)?

Hint:

*Consider implement these two helper functions:
getPredecessor(N), which returns the next smaller node to N.
getSuccessor(N), which returns the next larger node to N.
*Try to assume that each node has a parent pointer, it makes the problem much easier.
*Without parent pointer we just need to keep track of the path from the root to the current node using a stack.
*You would need two stacks to track the path in finding predecessor and successor node separately.
Hide Company Tags Google
Hide Tags Tree Stack
Hide Similar Problems (M) Binary Tree Inorder Traversal (E) Closest Binary Search Tree Value
``````

`preorder sequence: 14, 21, 24, 25, 28, 31, 32, 36, 39, 41, 47`
`target = 26.00`, `k = 3`

`stk1: 14, 21, 24, 25`
`stk2:28, 31, 32, 36, 39, 41, 47`;

``````/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<int> closestKValues(TreeNode* root, double target, int k) {
stack<int> predecessor;
stack<int> successor;
vector<int> res;
if(!root) return res;
inorderTraverse(root, target, false, predecessor);
inorderTraverse(root, target, true, successor);
while(k){
if(predecessor.empty()){
res.push_back(successor.top());
successor.pop();
}else if(successor.empty()){
res.push_back(predecessor.top());
predecessor.pop();
}else if(abs(predecessor.top() - target) < abs(successor.top() - target)){
res.push_back(predecessor.top());
predecessor.pop();
}else{
res.push_back(successor.top());
successor.pop();
}
--k;
}
return res;
}
void inorderTraverse(TreeNode* node, double target, bool reverse, stack<int>& stk){
if(!node) return;
inorderTraverse(reverse ? node->right : node->left, target, reverse, stk); // inorder traverse: left, root, right;
if((!reverse && node->val > target) || ( reverse && node->val <= target)) return;
stk.push(node->val);
inorderTraverse(reverse ? node->left : node->right, target, reverse, stk);// right.
}
};``````