首页 > 代码库 > leetcode 653. Two Sum IV - Input is a BST

leetcode 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   7Target = 9Output: True

 

Example 2:

Input:     5   /   3   6 / \   2   4   7Target = 28Output: 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