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; }
* }
*/
public class Solution {
public boolean findTarget(TreeNode root, int k) {
return checkTarget( root, k,new HashSet<Integer>() );
}
public boolean checkTarget(TreeNode root, int k, HashSet<Integer> s){
if(root==null)
return false;
int cha=k-root.val;
if(s.contains(cha))
return true;
s.add(root.val);
boolean left=checkTarget(root.left,k,s);
boolean right=checkTarget(root.right,k,s);
if(left||right)
return true;
return false;
}
}
使用根左右依次遍历所有节点,使用hashset去查找会否存在这两个元素