본문 바로가기

Algorithm/Brute Force

(C++) - LeetCode (easy) 653. Two Sum IV - Input is a BST

반응형

https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/

 

Two Sum IV - Input is a BST - LeetCode

Can you solve this real interview question? Two Sum IV - Input is a BST - 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.   Example 1: [http

leetcode.com

전수조사 문제였습니다.

📕 풀이방법

📔 입력 및 초기화

node의 각 원소를 key, 존재여부를 0또는 1로 나타내는 value로 valMap을 선언해 줍니다.

📔 풀이과정

재귀 함수 findTarget을 구현해줍니다.1. 기저 case(현재 node가 NULL)에서 false를 반환해줍니다.2. valMap에서 k - root->val이 이미 있다면 두 node 값의 합이 k이므로 true를 바로 반환해줍니다.3. 같지 않다면 해당 node 값을 valMap에 넣어줍니다.4. 왼쪽과 오른쪽 자식에 대해 수행하며 max값을 반환해줍니다.


📕 Code

📔 C++

/**
 * 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:
    map <int, int> valMap;
    bool findTarget(TreeNode* root, int k) {
        if(root==NULL) return false;
        if(valMap.count(k - root->val)) return true;
        valMap[root->val] = 1;
        return max(findTarget(root->left, k), findTarget(root->right, k));
    }
};

*더 나은 내용을 위한 지적, 조언은 언제나 환영합니다.