链接:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
题目: 判断BST中是否有两个原始的和等于k
思路: BST中序遍历的结果为有序数组;
然后再扫描数组判断即可(复杂度O(n))
代码:
class Solution {
public:
void inorder(TreeNode* root){
if(!root) return ;
if(root->left) inorder(root->left);
temp.push_back(root->val);
if(root->right) inorder(root->right);
}
bool findTarget(TreeNode* root, int k) {
inorder(root);
int l = 0;
int r = temp.size() - 1;
bool flag = 0;
while(l < r){
if(temp[l] + temp[r] == k) {
flag = 1;
break;
}
if(temp[l] + temp[r] < k) l++;
else r--;
}
return flag;
}
private:
vector<int>temp;
};