C++ Inorder with Deque


  • 0
    J

    Simple code with recursive Inorder and Deque in C++.

    class Solution {
    public:
        void inOrder(TreeNode* N, double target, int K, std::deque<int> & Q)
        {
            if(N==NULL)return;
            inOrder(N->left,target,K,Q);
            if(Q.size()<K)Q.push_back(N->val);
            else{
                if(abs(N->val-target)<abs(Q.front()-target)){
                    Q.pop_front();
                    Q.push_back(N->val);
                }
            }
            inOrder(N->right,target,K,Q);
        }
        vector<int> closestKValues(TreeNode* root, double target, int k) {
            std::deque<int> Q;
            vector<int> result;
            inOrder(root,target,k,Q);
            for(auto i=Q.begin();i!=Q.end();i++){
                result.push_back(*i);
            }
            return result;
        }
    };

Log in to reply
 

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