add: 220321-CN [cpp]

This commit is contained in:
Lam Haoyin 2022-03-22 00:50:34 +08:00
parent 88fe8cc916
commit ad2515ee45
No known key found for this signature in database
GPG Key ID: 8C089CB1A2B7544F
2 changed files with 37 additions and 1 deletions

36
cpp/2203/220321-CN.cpp Normal file
View File

@ -0,0 +1,36 @@
#include <functional>
#include <unordered_set>
/**
* 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<int> s;
std::function<void(const TreeNode*)> 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;
}
};

View File

@ -3,4 +3,4 @@ PROJECT(2203)
SET(CMAKE_CXX_STANDARD 23) SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2203 220321.cpp) ADD_EXECUTABLE(2203 220321-CN.cpp)