给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
TreeNode* node;
bool findTarget(TreeNode* root, int k) {
if(root == NULL)
return false;
node = root;
return GetAns(root, k);
}
bool GetAns(TreeNode* root, int k)
{
if(root == NULL)
return false;
int temp = k - root ->val;
TreeNode* t = Search(node, temp);
if(t != NULL && t != root)
return true;
return GetAns(root ->left, k) || GetAns(root ->right, k);
}
TreeNode* Search(TreeNode* root, int k)
{
if(root == NULL)
return NULL;
if(root ->val == k)
return root;
else if(root ->val > k)
return Search(root ->left, k);
else return Search(root ->right, k);
}
};