想不通啊。。。。。。
error code:
class Solution {
bool res;
public:
bool findTarget(TreeNode* root, int k) {
if(root==nullptr) return false;
find(root,k);
return res;
}
void find(TreeNode*root,int k){
if(root==nullptr) return;
k-=root->val;
fun(root->left,k);
fun(root->right,k);
k+=root->val;
find(root->left,k);
find(root->right,k);
}
void fun(TreeNode*root,int k){
if(root==nullptr) return;
if(root->val==k) {
res=true;
return;
}
else if(root->val<k) fun(root->left,k);
else fun(root->right,k);
}
};
correct code
思想:中序遍历二叉搜索树,得到的Vector从小到大递增,通过两个index遍历vector.
class Solution {
bool res;
public:
bool findTarget(TreeNode* root, int k) {
if(root==nullptr) return false;
vector<int>temp;
fun(root,temp);
int low=0,high=temp.size()-1;
while(low<high){
if(temp[low]+temp[high]==k) return true;
else if(temp[low]+temp[high]<k) low++;
else high--;
}
return false;
}
void fun(TreeNode* root,vector<int>&temp){
if(root==nullptr) return;
fun(root->left,temp);
temp.push_back(root->val);
fun(root->right,temp);
}
};