• 문제 링크
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);
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 661. Image Smoother - Java (0) | 2026.09.19 |
|---|---|
| [LeetCode] 657. Robot Return to Origin - Java (0) | 2026.09.18 |
| [LeetCode] 645. Set Mismatch - Java (0) | 2026.09.16 |
| [LeetCode] 643. Maximum Average Subarray I - Java (0) | 2026.09.15 |
| [LeetCode] 637. Average of Levels in Binary Tree - Java (0) | 2026.09.14 |
댓글