PROBLEM:
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
SOLVE:
/**
* 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) {
unordered_set<int> showed; //用unordered_set做,很简单的
return dfs(root,showed,k);
}
private:
bool dfs(TreeNode* root,unordered_set<int>& showed,int k){
//判断 目标值k-根节点值val 差是否在unordered_set中存在
if(!root)
return false;
if(showed.count(k-root->val))
return true;
showed.insert(root->val);
return dfs(root->left,showed,k)||dfs(root->right,showed,k);
}
};
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
//该方法使用的是二叉搜索法
return dfs(root, root, k);
}
private:
bool dfs(TreeNode* root, TreeNode* cur, int k){
//对 cur 节点进行扩展,同时对当前root和cur运用一次 search 方法
if(cur == NULL)return false;
return search(root, cur, k - cur->val) || dfs(root, cur->left, k) || dfs(root, cur->right, k);
}
bool search(TreeNode* root, TreeNode *cur, int value){
//对 root 节点进行扩展,同时判断此时的 root->val和cur->val 之和是否等于目标值(同时判断root和cur是否同一节点)
if(root == NULL)return false;
return (root->val == value) && (root != cur)
|| (root->val < value) && search(root->right, cur, value)
|| (root->val > value) && search(root->left, cur, value);
}
};
简介:第一种方法比较好懂,直接用unordered_set来存值遍历;第二种其实就是直接遍历,写得挺好。