16ms c++ stack implementation


  • 1
    T
    class Solution {
    public:
        vector<int> closestKValues(TreeNode* root, double target, int k) {
            vector<int> rst;
            stack<TreeNode*>stk;
            TreeNode *ptr = root;
            while (ptr || !stk.empty()) {
                if (ptr) {
                    stk.push(ptr);
                    ptr = ptr->left;
                }
                else {
                    ptr = stk.top(); stk.pop();
                    if (rst.size() == k && abs((double)rst.front()-target) > abs((double)ptr->val-target)) {
                        rst.erase(rst.begin());rst.push_back(ptr->val);
                    }
                    else if (rst.size() < k) rst.push_back(ptr->val);
                    else break;
                    ptr = ptr->right;
                }
            }
            return rst;
        }
    };
    

Log in to reply
 

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