-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1214-Two Sum BSTs.cpp
More file actions
30 lines (30 loc) · 906 Bytes
/
1214-Two Sum BSTs.cpp
File metadata and controls
30 lines (30 loc) · 906 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 search(TreeNode* root,int target)
{
if(!root)
return false;
if(root->val==target)
return true;
return target<root->val?search(root->left,target):search(root->right,target);
}
bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target)
{
if(!root1||!root2)
return false;
if(search(root2,target-root1->val))
return true;
if(root2->val<target-root1->val)
return twoSumBSTs(root1->left,root2->right,target)||twoSumBSTs(root1->right,root2,target);
return twoSumBSTs(root1->left,root2,target)||twoSumBSTs(root1->right,root2->left,target);
}
};