diff --git a/cpp/2203/220321-CN.cpp b/cpp/2203/220321-CN.cpp new file mode 100644 index 0000000..3165fd9 --- /dev/null +++ b/cpp/2203/220321-CN.cpp @@ -0,0 +1,36 @@ +#include +#include + +/** + * Definition for a binary tree node. + */ +struct TreeNode { + int val; + TreeNode* left; + TreeNode* right; + + explicit TreeNode(int x = 0, TreeNode* left = nullptr, TreeNode* right = nullptr) : val(x), left(left), right(right) {} +}; + +/** + * 653. Two Sum IV - Input is a BST + * Given the root of a Binary Search Tree and a target number k, return true if there exist two elements in the BST such that their sum is equal to the given target. + */ + +class Solution { +public: + static bool findTarget(const TreeNode* root, int k) { + if (!root) return false; + std::unordered_multiset s; + std::function traverse = [&](const TreeNode* ptr) { + s.insert(ptr->val); + if (ptr->left) traverse(ptr->left); + if (ptr->right) traverse(ptr->right); + }; + traverse(root); + for (int i : s) + if (s.count(k - i) > (((i * 2) == k) ? 1 : 0)) + return true; + return false; + } +}; diff --git a/cpp/2203/CMakeLists.txt b/cpp/2203/CMakeLists.txt index f8b6e44..bc7c4a4 100644 --- a/cpp/2203/CMakeLists.txt +++ b/cpp/2203/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2203) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2203 220321.cpp) +ADD_EXECUTABLE(2203 220321-CN.cpp)