https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
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
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
算法思路:
easy inorder and two-pointer technology
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector<int> arr;
inorder(root, arr);
int left = 0; int right = arr.size() - 1;
while (left < right) {
if (arr[left] + arr[right] == k) return true;
else if (arr[left] + arr[right] < k) left++;
else right--;
}
return false;
}
private:
void inorder(TreeNode* node, vector<int>& arr) {
if (node == nullptr) return;
inorder(node->left, arr);
arr.push_back(node->val);
inorder(node->right, arr);
}
};