1、题目描述
输入一个BST和一个target,如果树上两元素之和等于target返回true,反之返回false。
2、思路
对BST进行中序遍历,得到一个升序序列。再按照two sum II的方法用two pointers思路求解。
Time Complexity: O(n)
, Space Complexity: O(n)
.
3、代码
bool findTarget(TreeNode* root, int k) {
vector<int> nums;
inorder(root, nums);
for(int i = 0, j = nums.size()-1; i<j;){
if(nums[i] + nums[j] == k)return true;
(nums[i] + nums[j] < k)? i++ : j--;
}
return false;
}
void inorder(TreeNode* root, vector<int>& nums){
if(root == NULL)return;
inorder(root->left, nums);
nums.push_back(root->val);
inorder(root->right, nums);
}
4.拓展
若输入是一个普通二叉树,可用哈希表来求解。
Time Complexity: O(n)
, Space Complexity: O(n)
.
bool findTarget(TreeNode* root, int k) {
vector<int> v;
return dfs(root,v,k);
}
bool dfs(TreeNode* root,vector<int>& v, int k){
if(!root) return false;
if(find(v.begin(),v.end(),k-(root->val))!=v.end())
return true;
else{
v.push_back(root->val);
return dfs(root->left,v,k)||dfs(root->right,v,k);
}
}