描述:其实有点不懂这题的意思,因为在同样有序的条件下,BST是做不到有序数组那样两根指针搜索的,想要做到O(N),同样需要线性空间的HASHSET,这让我觉得使用BST这种数据结构来进行这种检验是得不偿失的,加上BST树还要考虑插入和平衡等问题,所以我觉得这题只是纯粹的为了拓展而拓展,不说那么多了,帖代码吧。注意这里HashSet的底层会在add方法中保证不同的数不会被添加,所以不用进行contains验证
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.
/**
* 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) {
HashSet<Integer> set = new HashSet<>();
return search(root,k,set);
}
private boolean search(TreeNode root ,int k,HashSet<Integer> set)
{
if(root==null)
return false;
if(set.contains(k-root.val))
return true;
set.add(root.val);
return search(root.left,k,set)||search(root.right,k,set);
}
}