首页 > 其他 > 详细

leetcode 653. Two Sum IV - Input is a BST

时间:2017-08-07 11:11:17      阅读:250      评论: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

遍历整颗bst,中序遍历可以得到一个有序的数组,这里可以用二分查找,也可以用map搞两个数的和,也可以用set边遍历边查找。

class Solution {
public:
    vector<int>v;
    void dfs(TreeNode * root) {
        if (root == NULL) return ;
        dfs(root->left);
        v.push_back(root->val);
        dfs(root->right);
    }
    bool findTarget(TreeNode* root, int k) {
        dfs(root);
        //cout << v.size() <<endl;
        map<int,int>mp;
        for (int i = 0; i < v.size(); ++i) {
            if (mp.count(k - v[i]) > 0) {
                return true;
            }
            mp[v[i]] = 1;
        }
        return false;
    }
};

 

class Solution {
private:
    unordered_set<int> uset;
public:
    bool findTarget(TreeNode* root, int k) {
        if (!root) return false;
        int val = root->val;
        if (uset.count(k-val)) return true;
        else {
            uset.insert(val);
            return findTarget(root->left, k) || findTarget(root->right, k);
        }
        return false;
    }
};

 

leetcode 653. Two Sum IV - Input is a BST

原文:http://www.cnblogs.com/pk28/p/7297898.html

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