There is a very simple idea to keep a max heap of size K and elements in the heap was sorted by their absolute di Fference from target. For the Max Heap, we'll simply use the default priority_queue. Then we simply traverse the tree and push all it nodes to the heap while maintaining the size of the heap not larger than k.
The code is as follows.
1 classSolution {2 Public:3vector<int> closestkvalues (treenode* root,DoubleTargetintk) {4priority_queue<pair<Double,int>>PQ;5 Closestk (Root, PQ, Target, k);6vector<int>closest;7 while(!pq.empty ())8 Closest.push_back (Pq.top (). Second), Pq.pop ();9 returnclosest;Ten } One Private: A voidCLOSESTK (treenode* node, priority_queue<pair<Double,int>>& PQ,DoubleTargetintk) { - if(!node)return; -Pq.push (Make_pair (ABS (Target-node, Val), node-val)); the if(Pq.size () >k) Pq.pop (); -CLOSESTK (Node-Left , PQ, Target, k); -CLOSESTK (Node-Right , PQ, Target, k); - } +};
[Leetcode] Closest Binary Search Tree Value II