题目描述:
给定一个二叉搜索树和一个目标结果,如果 BST 中存在两个元素且它们的和等于给定的目标结果,则返回 true。
案例 1:
案例 2:
C++代码如下:
/**
* 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) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
vector<int>v;
dfs(root,v);
int size=v.size();
int low=0,high=size-1;
bool flag=false;
while(low<high){
if(v[low]+v[high]==k){
flag=true;
return flag;
} else if (v[low]+v[high]<k){
low++;
} else if (v[low]+v[high]>k){
high--;
}
}
return flag;
}
void dfs(TreeNode* root,vector<int>&v){
if(root==nullptr){
return;
}
//BST采用中序遍历就是一个有序数组,不需要重新排序了
dfs(root->left,v);
v.push_back(root->val);
dfs(root->right,v);
}
};
JAVA 代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public boolean findTarget(TreeNode root, int k) {
List<Integer> arr = new ArrayList<>();
DFS(root, arr);
int left = 0, right = arr.size() - 1;
while (left < right) {
if (arr.get(left) + arr.get(right) == k) {
return true;
} else if (arr.get(left) + arr.get(right) < k) {
left++;
} else if (arr.get(left) + arr.get(right) > k) {
right--;
}
}
return false;
}
public void DFS(TreeNode root, List<Integer> list) {
if (root == null) {
return;
}
DFS(root.left, list);
list.add(root.val);
DFS(root.right, list);
}
}
执行结果: