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
用了最蠢的办法把节点先全部保存起来,再循环找到和为k的点
之前一直在用树递归写,思路大致是每个节点上先将k减去当前节点的val,然后再遍历当前节点的左右子树,相当于在bst树上进行查找值为k-val的点,一旦找到就返回true,但是一直没写对,,再看看。
class Solution {
public:
bool findTarget(struct TreeNode* root, int k)
{
vector<int> temp;
int i,j;
inorder(root,temp);
for(i=0;i<temp.size();i++){
for(j=i+1;j<temp.size();j++){
if(temp[i]+temp[j]==k) return true;
}
}
return false;
}
void inorder(struct TreeNode* root,vector<int>& temp)
{
if(root==NULL) return;
temp.push_back(root->val);
inorder(root->left,temp);
inorder(root->right,temp);
}
};