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:

True

Example 2:

Input:

    5
/ \
3 6
/ \ \
2 4 7

Target = 28

Output:

False

分析

题目的意思是:给定一颗二叉树,判断是否存在两个数的和为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 两数之和之四 - 输入是二叉搜索树​