您的位置:首页 > 其它

leetcode 653. Two Sum IV - Input is a BST

2017-08-07 10:30 483 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: