首页 > 其他 > 详细

653. Two Sum IV - Input is a BST

时间:2018-10-11 12:51:54      阅读:131      评论:0      收藏:0      [点我收藏+]

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

原文:https://www.cnblogs.com/jessie2009/p/9771737.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!