C++ using one stack and one queue


  • 0
    class Solution {
    public:
        vector<int> closestKValues(TreeNode* root, double target, int k) {
            stack<int> less;
            queue<int> more;
            stack<TreeNode*> stk;
            TreeNode *node = root;
            while(node!=nullptr || !stk.empty()) {
                if(node!=nullptr) {
                    stk.push(node);
                    node = node->left;
                } else {
                    node = stk.top();
                    if(node->val < target) less.push(node->val);
                    else more.push(node->val);
                    stk.pop();
                    node = node->right;
                }
            }
            vector<int> ans;
            while(k>0) {
                if(more.empty()){
                    ans.push_back(less.top());
                    less.pop();
                } else if(less.empty()) {
                    ans.push_back(more.front());
                    more.pop();
                } else if(target-less.top() < more.front()-target) {
                    ans.push_back(less.top());
                    less.pop();
                } else if(target-less.top() >= more.front()-target) {
                    ans.push_back(more.front());
                    more.pop();
                }
                k--;
            }
            return ans;
        }
    };
    

Log in to reply
 

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