Simple C++ using std::set() and std::min_element()


  • 0
    class Solution {
    public:
        int findSecondMinimumValue(TreeNode* root) {
            if (!root) { return -1; }
            queue<TreeNode*> q{}; q.push(root);
            set<int> nums{};
            while (!q.empty()){
                TreeNode* node=q.front();
                q.pop();
                nums.insert(node->val);
                if (node->left) { q.push(node->left); }
                if (node->right) { q.push(node->right); }
            }
            nums.erase(min_element(nums.begin(),nums.end()));
            set<int>::iterator itr = min_element(nums.begin(),nums.end());
            if (itr == nums.end()) { return -1; }
            return *itr;
        }
    };
    

Log in to reply
 

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