반응형
https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
Two Sum IV - Input is a BST - LeetCode
Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.
leetcode.com
모든 노드를 순회하면서 방문하는 수를 저장해줍니다.
(k - 현재 노드의 값)이 저장되어 있다면, 두 수의 합으로 k를 만들 수 있음을 의미합니다.
class Solution {
public:
set<int> values;
bool findTarget(TreeNode* root, int k) {
if(!root) return false;
if(values.find(k - root->val) != values.end()) return true;
values.insert(root->val);
return findTarget(root->left, k) || findTarget(root->right, k);
}
};
반응형
'Algorithm' 카테고리의 다른 글
LeetCode 451 : Sort Characters By Frequency (1) | 2022.12.03 |
---|---|
LeetCode 899 : Orderly Queue (0) | 2022.11.06 |
LeetCode 16 : 3Sum Closest (1) | 2022.10.08 |
LeetCode 393 : UTF-8 Validation (0) | 2022.09.13 |
LeetCode 1996 : The Number of Weak Characters in the Game (0) | 2022.09.09 |