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
//Time: O(n), Space: O(n)   
//开始以为BST用二分,后来发现这道题和二叉搜索树没啥关系,就是遍历一颗普通的二叉树
 public boolean findTarget(TreeNode root, int k) {
        if (root == null) {
            return false;
        }
        
        HashSet<Integer> set = new HashSet<Integer>();
        return dfs(root, k, set);
    }
    
    private boolean dfs(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 dfs(root.left, k, set) || dfs(root.right, k, set);
    }

 

posted @ 2018-10-11 12:21  一丝清风一抹红尘  阅读(90)  评论(0编辑  收藏  举报