653. Two Sum IV - Input is a BST
【思路】:
- 一般采用深度遍历;
- 和= 顶点+ 右子树 || 左子树+ 右子树 || 左子树+顶点;
- 使用中序遍历获得顺序,然后通过前后相加比较;
- Leetcode 653. Two Sum IV - Input is a BST
bool findTarget(TreeNode* root, int k) {
vector<int> res;
dfs_inorder(root,res);
int sum=0;
int len = res.size();
int i=0;
int j = len-1;
cout<<"size: "<<len<<endl;
while(i<len){
sum = res[i] + res[j];
if(sum > k)
j --;
else if(sum < k)
i++;
else
return true;
}
return false;
}
// DFS
void dfs_inorder(TreeNode* root, vector<int>& res){
if(! root )return;
//cout<<"val: "<<root->val<<endl;
dfs_inorder(root->left,res);
res.push_back(root->val);
dfs_inorder(root->right,res);
}