Two Sum BSTs
给两个bst, 然后看是不是能做two sum.
先用inorder变成array, 然后做two sum.
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
vector<int> v;
inorder(root1, v);
return twosum(v, root2, target);
}
void inorder(TreeNode* root, vector<int>& v){
if(!root)
return;
inorder(root->left, v);
v.push_back(root->val);
inorder(root->right, v);
}
bool twosum(vector<int>& v, TreeNode* root, int t) {
if(!root)
return false;
return binary_search(v.begin(), v.end(), t - root->val) || twosum(v, root->left, t) || twosum(v, root->right, t);;
}
};