您的位置 首页 JAVA(2017)

653. Two Sum IV – Input is a BST

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) {
        if(root == null) return false;
        HashSet map = new HashSet();
        return checkk(root,k,map);
    }
    public boolean checkk(TreeNode root, int k,HashSet map){
        if(root == null) return false;
        if(map.contains(k-root.val)) return true;
        map.add(root.val);
        return checkk(root.left,k,map) || checkk(root.right,k,map);
    }
}
看完了?留个评分呗?
[0人评了分,平均: 0/5]

本站原创文章皆遵循“署名-非商业性使用-相同方式共享 3.0 (CC BY-NC-SA 3.0)”。转载请保留以下标注:

原文来源:《653. Two Sum IV – Input is a BST》

发表评论

电子邮件地址不会被公开。

返回顶部