653. Two Sum IV - Input is a BST

Posted jessie2009

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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);
    }

 

以上是关于653. Two Sum IV - Input is a BST的主要内容,如果未能解决你的问题,请参考以下文章

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

653. Two Sum IV - Input is a BST

[leetcode-653-Two Sum IV - Input is a BST]

leetcode 653. Two Sum IV - Input is a BST

LeetCode 653. Two Sum IV - Input is a BST