-
[LeetCode] 653. Two Sum IV - Input is a BST c++Coding Test/LeetCode 2023. 2. 22. 18:43728x90
문제
Given the root of a binary search tree and an integer k, return true if there exist two elements in the BST such that their sum is equal to k, or false otherwise.
문제 해결
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode() : val(0), left(nullptr), right(nullptr) {} * TreeNode(int x) : val(x), left(nullptr), right(nullptr) {} * TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {} * }; */ class Solution { public: bool findTarget(TreeNode* root, int k) { if (!root){ return false; } if (s.count(k - root->val)){ return true; } s.insert(root->val); return findTarget(root->left, k) || findTarget(root->right, k); } private: unordered_set<int> s; };
728x90'Coding Test > LeetCode' 카테고리의 다른 글
[LeetCode] 1464. Maximum Product of Two Elements in an Array c++ (0) 2023.02.21 [LeetCode] 206. Reverse Linked List c++ (0) 2023.01.04 [LeetCode] 21. Merge Two Sorted Lists c++ (0) 2023.01.04 [LeetCode] 994. Rotting Oranges c++ (0) 2023.01.04 [LeetCode] 542. 01 Matrix c++ (0) 2023.01.03