0
点赞
收藏
分享

微信扫一扫

653. Two Sum IV - Input is a BST

楚木巽 2022-08-03 阅读 73


Given a Binary Search Tree and a target number, return true if there exist two elements in the BST such that their sum is equal to the given target.

Example 1:

Input: 
5
/ \
3 6
/ \ \
2 4 7

Target = 9

Output: True

Example 2:

Input: 
5
/ \
3 6
/ \ \
2 4 7

Target = 28

Output: False

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
return find(root, new HashSet<>(), k);
}

public boolean find(TreeNode root, HashSet<Integer> mem, int k){
if (root == null) return false;
if (mem.contains(k - root.val)) return true;
mem.add(root.val);
return


举报

相关推荐

0 条评论