leetcode 653 两数之和 IV - 输入BST
思路
- 前序遍历 BST,转为数组;
- 此时数组有序,双指针不断接近 target;
题解
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector<int> res;
inorder(root,res);
int left = 0;
int right = res.size()-1;
while(left < right) {
int sum = res[left] + res[right];
if(sum == k) return true;
else if(sum < k) {
left++;
} else {
right--;
}
}
return false;
}
void inorder(TreeNode *root,vector<int> &res) {
if(root != NULL) {
inorder(root->left,res);
res.push_back(root->val);
inorder(root->right,res);
}
}
};