[leetcode] 653. Two Sum IV - Input is a BST
原创
©著作权归作者所有:来自51CTO博客作者是念的原创作品,请联系作者获取转载授权,否则将追究法律责任
Description
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:
Example 2:
Input:
5
/ \
3 6
/ \ \
2 4 7
Target = 28
Output:
分析
题目的意思是:给定一颗二叉树,判断是否存在两个数的和为target。
- 用一个set集合s把来存储每个节点的值,如果再遇见一个target-当前值存在这个集合里面,说明存在两个数,就直接返回正确了。
代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
if(!root) return false;
unordered_set<int> s;
return solve(root,k,s);
}
bool solve(TreeNode* root, int k,unordered_set<int> &s){
if(!root){
return false;
}
if(s.count(k-root->val)){
return true;
}
s.insert(root->val);
return solve(root->left,k,s)||solve(root->right,k,s);
}
};
参考文献
[LeetCode] Two Sum IV - Input is a BST 两数之和之四 - 输入是二叉搜索树