653. Two Sum IV - Input is a BST

描述:其实有点不懂这题的意思,因为在同样有序的条件下,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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容