1.问题描述
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
2.算法分析
该问题与普通Two Sum的区别在于是在二分搜索树中寻找两个加数。利用二分搜索树的特性,即根结点的值不小于左子树的值,且不大于右子树的值,所以首先利用中序遍历把二分搜索树转换为一个普通的有序数组,再在有序数组中使用两个指针同时从一头一尾进行遍历。需要使用额外的空间O(n).
3.代码实现
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
void inOrder( TreeNode *root, vector<int> &vec){
if(root == NULL) return;
inOrder(root->left, vec);
vec.push_back(root->val);
inOrder(root->right, vec);
}
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector <int> vec;
inOrder(root, vec);
int i = 0, j = vec.size() - 1;
while(i < j){
if(vec[i] + vec[j] == k)
return true;
else if(vec[i] + vec[j] > k)
j--;
else
i++;
}
return false;
}
};