diff --git a/cpp/2204/220418.cpp b/cpp/2204/220418.cpp new file mode 100644 index 0000000..c26fad7 --- /dev/null +++ b/cpp/2204/220418.cpp @@ -0,0 +1,40 @@ +#include +#include +#include +#include + +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* l = nullptr, TreeNode* r = nullptr) : val(x), left(l), right(r) {} +}; + +class Solution { +private: + static int priorityQueue(TreeNode* root, int k) { + std::vector val; + std::function f = [&](TreeNode* ptr) { + if (!ptr) return; + val.push_back(ptr->val); + if (ptr->left) f(ptr->left); + if (ptr->right) f(ptr->right); + }; + + // O(n) + f(root); + + // O(n) + std::priority_queue, std::greater<>> q(val.begin(), val.end()); + + // O(k * log(n)) + for (int i = 1; i < k; ++i) + q.pop(); + return q.top(); + } +public: + static int kthSmallest(TreeNode* root, int k) { + return priorityQueue(root, k); + } +}; diff --git a/cpp/2204/CMakeLists.txt b/cpp/2204/CMakeLists.txt index 3e60554..82d1ed7 100644 --- a/cpp/2204/CMakeLists.txt +++ b/cpp/2204/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2204) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2204 220418-CN.cpp) +ADD_EXECUTABLE(2204 220418.cpp)