[LeetCode] Two Sum BSTs

1214. Two Sum BSTs

Given the roots of two binary search trees, root1 and root2, return true if and only if there is a node in the first tree and a node in the second tree whose values sum up to a given integer target.

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
/**
* 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 {
bool find(TreeNode* node, int val) {
if(!node) return false;
if(node->val == val) return true;
if(node->val < val) return find(node->right, val);
return find(node->left, val);
}
public:
bool twoSumBSTs(TreeNode* root1, TreeNode* root2, int target) {
if(!root1) return false;
if(find(root2, target - root1->val)) return true;

return twoSumBSTs(root1->left, root2, target) or twoSumBSTs(root1->right, root2, target);
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/06/14/PS/LeetCode/two-sum-bsts/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.