Sharing my 20ms C++ solution


  • 0
    T
    /**
     * 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 {
    private:
        vector<int> convertQueueToVector(queue<int> myQueue)
        {
            vector<int> myVector;
            while(myQueue.size() > 0)
            {
                myVector.push_back(myQueue.front());
                myQueue.pop();
            }
            return myVector;
        }
        
        void closestKValuesHelper(TreeNode* root, double target, int k, queue<int>& myQueue)
        {
            if(root==NULL)
                return;
            closestKValuesHelper(root->left, target, k, myQueue);
            
            if(myQueue.size() < k)
                myQueue.push(root->val);
            else
            {
                if(fabs(root->val-target) < fabs(myQueue.front()-target))
                {
                    myQueue.pop();
                    myQueue.push(root->val);
                }
                else
                    return;
            }
            
            closestKValuesHelper(root->right, target, k, myQueue);
        }
        
    public:
        vector<int> closestKValues(TreeNode* root, double target, int k) {
            queue<int> myQueue;
            closestKValuesHelper(root, target, k, myQueue);
            return convertQueueToVector(myQueue); 
        }
    };

  • 0
    I

    Why do you check to see if the root node is closer to target than the node at front of queue?


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.