题目解析:
题目链接:https://leetcode.com/problems/two-sum-iv-input-is-a-bst/description/
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
解题思路:
该题给了一个二叉搜索树,第一反应是将该树转成一个顺序数组vector<int> v,然后进行查找。由于得到的数组是升序排列,因而从两边求和对比,v[i]+v[j] == k返回true,v[i]+v[j]>k,j--,否则,i++。当i>=j时候跳出。于是动手实现,代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
stack<TreeNode*> s;
vector<int> v;
while(root||!s.empty())
{
if(root)
{
s.push(root);
root = root->left;
}
else
{
root=s.top();
v.push_back(root->val);
s.pop();
root=root->right;
}
}
int l = 0;
int r = v.size()-1;
while(l < r)
{
if(v[l]+v[r] < k)
{
l++;
continue;
}
if(v[l]+v[k]>k)
{
r--;
continue;
}
if (v[l]+v[k] == k)
return true;
}
return false;
}
};
然而,理想很丰满。提交之后发现 超时 了。
Submission Result: Time Limit Exceeded More Details
class Solution {
public:
bool findTarget(TreeNode* root, int k) {
//vector<int> v;
convTree2Vec(root);
int l = 0;
int r = v.size()-1;
while(l < r)
{
if(v[l]+v[r] < k)
{
l++;
continue;
}
if(v[l]+v[r]>k)
{
r--;
continue;
}
if (v[l]+v[r] == k)
return true;
}
return false;
}
vector<int> v;
void convTree2Vec(TreeNode* root)
{
if(!root)
return ;
convTree2Vec(root->left);
v.push_back(root->val);
convTree2Vec(root->right);
}
};
看了看排名靠前的大神的代码。思想就是用k减去当前节点值,然后进行搜索,用这个差跟其他节点做对比,如果有相等的就返回true。没相等的就更新当前节点,再进行循环。
class Solution {
public:
bool dfs(TreeNode* root, int val, TreeNode* used) {
if (root == nullptr) return false;
if (root != used && root->val == val) return true;
if (root->val > val) return dfs(root->left, val, used);
else return dfs(root->right, val, used);
}
bool travel(TreeNode* root, TreeNode* cur, int k) {
if (cur == nullptr) return false;
return (dfs(root, k - cur->val, cur) || travel(root, cur->left, k) || travel(root, cur->right, k));
}
bool findTarget(TreeNode* root, int k) {
return travel(root, root, k);
}
};