본문 바로가기
Problem Solving/LeetCode

[LeetCode] 653. Two Sum IV - Input is a BST - Java

by graycode 2026. 9. 17.

• 문제 링크

 

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

 

• 풀이 코드

import java.util.HashSet;
import java.util.Set;

public class Solution {

    Set<Integer> set = new HashSet<>();
    int tgt;

    public boolean findTarget(TreeNode root, int k) {
        tgt = k;
        return dfs(root);
    }

    private boolean dfs(TreeNode node) {
        if (node == null) return false;

        if (set.contains(tgt - node.val)) return true;
        set.add(node.val);

        return dfs(node.left) || dfs(node.right);
    }

}

댓글